If I have a try ... catch
block inside a while
loop, and there#s a break
inside the catch
, does program execution leave the loop?
As in:
while (!finished) { try { doStuff(); } catch (Exception e) { break; } }
Will an exception thrown in doStuff() exit the loop?
The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement: public void someMethod() { try { ... if (condition) return; ... } catch (SomeException e) { ... } }
If a break statement occurs inside a try statement, control may not immediately transfer to the target statement. If a try statement has a finally clause, the finally block is executed before control leaves the try statement for any reason.
If you have try catch within the loop it gets executed completely inspite of exceptions.
Yes, it will. Easiest way to find out is to try it.
public static void main(String[] args) { int i=0; while (i<10) { System.out.println(i); try { if(i ==7){ throw new Exception(); } i++; } catch (Exception e) { break; } } System.out.println("out of loop"); }
It will print
0 1 2 3 4 5 6 7 out of loop
The output starts with 0.
A break
statement always applies to the innermost while
, do
, or switch
, regardless of other intervening statements. However, there is one case where the break
will not cause the loop to exit:
while (!finished) { try { doStuff(); } catch (Exception e) { break; } finally { continue; } }
Here, the abrupt completion of the finally
is the cause of the abrupt completion of the try
, and the abrupt completion of the catch
is lost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With