• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java, exceptions and iterations help

 
Lance Walker
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49472
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
>
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic