• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Java, exceptions and iterations help

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
>
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic