java異常體系---不要在finally塊中使用return、throw

在finally塊中使用return、throw,會致使編譯告警:finally block does not complete normally。

狀況一:finally塊中沒retrun、throw

複製代碼

public static void method_1() {
    try {
        System.out.println("try block run");
        throw new Exception("try block 異常");
    } finally {
        System.out.println("finally block run");
    }
}

public static void method_2() {
    try {
        System.out.println("try block run");
    } catch (Exception e) {
        System.out.println("catch block run");
        throw new Exception("catch block 異常了!");
    } finally {
        System.out.println("finally block run");
    }
}

複製代碼

 說明:程序報錯,Unhandled exception type Exception。此時編譯器會檢查try塊、catch塊中的非運行時異常。spa

狀況二:finally塊中有retrun或者throw

複製代碼

public static void method_1() {
    try {
        System.out.println("try block run");
        throw new Exception("try block 異常");
    } finally {
        System.out.println("finally block run");
        return;
    }
}
程序運行結果:try block run   》》  finally block run

public static void method_2(){
    try{
        System.out.println("try block run");   
    }catch (Exception e) {
        System.out.println("catch block run");
        throw new Exception("catch block 異常了!");
    }finally{
        System.out.println("finally block run");
        throw new RuntimeException("finally block 異常了!");
    }    
}
程序運行結果:try block run   》》  finally block run  》》  finally block 異常了!

複製代碼

說明:程序告警,finally block does not complete normally。此時編譯器不會檢查try塊、catch塊中的非運行時異常。orm

JVM不會再去捕獲try塊、catch塊中的異常,而是獲得(使用return時)finally塊的返回值或者(使用throw時)finally塊中拋出的異常。編譯器

結論:

當在finally塊中使用return、throw時,編譯器不會再對try、catch塊中的非運行時異常進行檢查,JVM不會再去捕獲try塊、catch塊中的異常,程序的輸出以finally塊爲準,即finally塊的返回值或者finally塊中拋出的異常。io

當在try塊或catch塊中遇到return語句時,finally塊將在方法返回以前被執行。finally塊中的return語句會覆蓋try塊、catch塊中的return語句。合理的作法是在 finally 塊以後使用return語句。編譯

相關文章
相關標籤/搜索