my dog learned polymorphism
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

Java, exceptions and iterations help

Lance Walker

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

Joined: Oct 13, 2005
Posts: 46367
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

Joined: Jan 28, 2003
Posts: 4181

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.


I agree. Here's the link:
subject: Java, exceptions and iterations help
It's not a secret anymore!