Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a break leave just the try/catch or the surrounding loop?

Tags:

java

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?

like image 872
Hanno Fietz Avatar asked May 06 '11 11:05

Hanno Fietz


People also ask

How do you break out of a try statement?

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) { ... } }

Can we use break in try catch in Java?

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.

Can I put try catch inside for loop?

If you have try catch within the loop it gets executed completely inspite of exceptions.


2 Answers

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.

like image 117
fmucar Avatar answered Sep 24 '22 15:09

fmucar


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.

like image 26
Nathan Ryan Avatar answered Sep 20 '22 15:09

Nathan Ryan