try catch 应该放在for里还是不该放for里

这个问题我也很疑惑,所以自己写了test来给自己解惑下

try catch在for循环外面,并且,catch 只答应日志,不抛出异常

public static void main(String[] args) {
        try {
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
                int i1 = 1;
                System.out.println(i1 / i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("是否继续");

    }
java.lang.ArithmeticException: / by zero
0
    at com.linewell.zhzf.api.gateway.gateway.Test.main(Test.java:14)
是否继续

Process finished with exit code 0

try catch在for 循环外面就直接抛出异常,就不继续执行for循环里的业务了,继续走for循环外面的业务。

public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(i);
                int i1 = 1;
                System.out.println(i1 / i);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("是否继续");
    }
0
java.lang.ArithmeticException: / by zero
1
1
    at com.linewell.zhzf.api.gateway.gateway.Test.main(Test.java:15)
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
0
是否继续

Process finished with exit code 0

如果在for 循环里的话,就继续走for循环里的其他值操作。

  public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(i);
                int i1 = 1;
                System.out.println(i1 / i);
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
        System.out.println("是否继续");
    }
0
Exception in thread "main" java.lang.RuntimeException
    at com.linewell.zhzf.api.gateway.gateway.Test.main(Test.java:17)

Process finished with exit code 1

这里直接throw 一个异常出去,就不继续for循环了,并且for循环外面也不执行了。

 public static void main(String[] args) {
        try {
            for (int i = 0; i < 10; i++) {

                System.out.println(i);
                int i1 = 1;
                System.out.println(i1 / i);

            }
        } catch (Exception e) {
            throw new RuntimeException();
        }
        System.out.println("是否继续");
    }
0
Exception in thread "main" java.lang.RuntimeException
    at com.linewell.zhzf.api.gateway.gateway.Test.main(Test.java:17)

Process finished with exit code 1

这里直接throw 一个异常出去,也是走一次。

结论:

如果catch里throw new RuntimeException() 那么建议直接写for循环外面。

如果catch发生后,还要继续在for里循环执行,建议写在for循环里,并且不要throw异常。

原文地址:https://www.cnblogs.com/xuerong/p/9341733.html