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異常。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM