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

后端 未结 6 839
花落未央
花落未央 2020-12-29 01:28

If I have a try ... catch block inside a while loop, and there#s a break inside the catch, does program execution leave t

6条回答
  •  时光取名叫无心
    2020-12-29 02:07

    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.

提交回复
热议问题