• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to break out of a loop if there is an indexOutOfBoundException?  RSS feed

 
Bob Ivanovich
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to break out of a loop if there is an indexOutOfBoundException? For example:

 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bob Ivanovich wrote:Is it possible to break out of a loop if there is an indexOutOfBoundException?

Sure. With a try...catch block.

Possibly a better question is: Do you really want to?

Without knowing exactly what you're trying to do, it's difficult to say; but it sounds like using exception logic to drive program flow to me - and that's usually NOT a good thing.

Winston
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
generally, if you have an array, you know the size before going INTO the loop. So a for-loop might make more sense. if that's not possible, you can always do


Although there still may be an even better way, depending on your real requirements.
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
not only what Fred said, but(in java7 anyway) we now have a "for each" loop. it automatically ends when it finishes going through the entire array.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!