开发者

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

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?


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.


Yes, it'll break the loop.

But why not do:

finished = true;

instead?


Yes. break exists loop and switch statements.


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.


Yes, It does. break exit from while loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜