File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Java, exceptions and iterations help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java, exceptions and iterations help" Watch "Java, exceptions and iterations help" New topic
Author

Java, exceptions and iterations help

Lance Walker
Greenhorn

Joined: Mar 09, 2009
Posts: 23
Hi, I need to make a loop that iterates through a list of servers to connect to, and if it connects to one successful, breaks the loop. If a particular server rejects the connection, then an exception is thrown. How can I make it so that it skips the failed server and tries the next one? I didn't think I was doing anything wrong, but it still continues to try to connect to the same server, over and over again. Heres the basic idea of what I'm trying to do, but whenever I implement it into real code it doesn't work:

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36501
    
  16
Try a boolean isConnected = false; before the loop, and at the end of the try isConnected = true; Then you can add !isConnected to the middle part of the for-loop heading.
Why are you only incrementing your counter in the catch? That may cause you to go into an infinite loop.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 3948
    
  17

I suspect the problem is in some code you didn't show us. Why? See the code at the bottom of this post. When I make your code compilable and test the logic it runs as expected. So here is what you should do:
1) Tell us exactly how it doesn't work. Do you get an exception, does the program crash? What exactly is the behavior, and how does that contrast with what you expect to happen?
2) Show us the real code. Make a small, compilable, demonstration application that misbehaves the same way your real code does, and show us this sample (it is called making a SSCCE. Who knows, perhaps in the process of making the SSCCE you will find the error and fix it.


My example SSCCE based on your code.
Expect it to report failure 2 times, then succeed on the third.
Results:

Code:
>


Steve
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Java, exceptions and iterations help
 
Similar Threads
getting batchupdate exception while inserting recored for second time...
Connecting to DB Error
Question about string immutable
save file to remote server from an applet
Fake a post request from java class