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

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

Yes, it'll break the loop.

But why not do:

finished = true;

instead?

Solution 4 - Java

Yes. break exists loop and switch statements.

Solution 5 - Java

> Will an exception thrown in doStuff() > exit the loop?

Step by step, here is what will happen:

  1. The exception is thrown in doStuff()
  2. Your "eat all Exceptions" handler will catch the exception.
  3. The "break" statement will leave the while loop.

Solution 6 - Java

Yes, It does. break exit from while loop.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHanno FietzView Question on Stackoverflow
Solution 1 - JavafmucarView Answer on Stackoverflow
Solution 2 - JavaNathan RyanView Answer on Stackoverflow
Solution 3 - JavaAlnitakView Answer on Stackoverflow
Solution 4 - JavaXionView Answer on Stackoverflow
Solution 5 - JavaBob CrossView Answer on Stackoverflow
Solution 6 - JavaHeisenbugView Answer on Stackoverflow