2

What is the difference between:

while( true ) {
    try {
        // something 
    } catch( Exception e ) {
        break; 
    }
}

and

try {
    while( true ) {
    // something 
    // break; // eventually
    }
} catch( Exception e ) {

}

Does the former run a try-catch on every iteration or does the compiler generate the same code. Which is preferred?

EDIT: break; was removed from catch block in second example since there is no need.

BAR
  • 15,909
  • 27
  • 97
  • 185
  • Not only is there no need for the `break` in the second example, as seen in my answer it's forbidden to be there. – jlordo Feb 27 '13 at 07:06

1 Answers1

6

The difference is, that the firs one will compile and work as expected (break out of the loop when an exception occurs) and the second one won't compile.

The compiler error will be break cannot be used outside of a loop or a switch which is pretty much self explaining (you are trying to use break outside of a loop (syntactically), and that's not allowed).

I'll modify your example to illustrate this:

try {
    while( true ) {
    // something 
    // break; // eventually
    }
    /* --> more code, that could throw an exception <-- */
} catch( Exception e ) {
    break; 
}

If the exception occurs where I inserted the comment, what should be broken out of?

To explictly answer your questions:

Does the former run a try-catch on every iteration or does the compiler generate the same code?

Yes, the former runs a try/catch block on every iteration.

Which is preferred?

The first one, obviously.

The preferred way is the second way, just without the break keyword in the catch block. As Ren pointed out in his comment, when an exception occurs you will execute the catch block (logging error or something like that) and then the code below the catch block get's executed. No need for the break keyword.

jlordo
  • 37,490
  • 6
  • 58
  • 83
  • So a try-catch is preferred on every iteration? It seems counter intuitive to me assuming it will involve extra overhead as opposed to running it once. – BAR Feb 26 '13 at 23:31
  • @user417896: I agree with your chain of thought. But the other way it isn't possible, so yes, the preferred way is the way without compiler errors. – jlordo Feb 26 '13 at 23:33
  • 2
    With the second approach, you're going into the catch block, which is outside the loop, when an exception. So you don't need a break there. – Ren Feb 26 '13 at 23:37
  • I knew the question was a valid one, and particularly easy to get wrong. Thanks for the updated reply. – BAR Feb 27 '13 at 03:43
  • @user417896: Make sure the exception occurs sooner or later, or this will be an infinite loop. – jlordo Feb 27 '13 at 07:06