简体   繁体   中英

Java try-catch inside of while loop or outside

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM