try catch放在for循环的里面还是外面好

try放在for循环里面和外面的区别?先看看下面代码的区别:

public class Test {
    public void test1(){
        for (int count = 0; count < 6; count++) {
            try {
                int x;
                if (count == 3)
                    x = 1 / 0;
                else{
                    x = count;
                    System.out.println(x);
                }

            } catch(Exception e){
                System.out.println("异常");
            }
        }
    }

结果:

0
1
2
异常
4
5

public void test2(){
        try {
            for (int count = 0; count < 6; count++) {
                int x;
                if (count == 3)
                    x = 1 / 0;
                else{
                    x = count;
                    System.out.println(x);
                }
            }   
        } catch (Exception e) {
            System.out.println("异常");
        }
       
    }

    public static void main(String[] args) throws Exception {
        Test te = new Test();
        te.test1();
        System.out.println("------------------------");
        te.test2();
    }
}

结果

0
1
2
异常


----------------------------------------------------------------------------------------------------------------


总结:try放在for循环的里面所有的for循环都会执行,当遇到异常时,抛出异常继续执行;

放在外面,当遇到异常时,抛出异常,后面的循环就会终止,并不会执行。

猜你喜欢

转载自blog.csdn.net/qq_16946803/article/details/85335548