java異常finally相關執行順序

package com.core;

public class TestException2 {  
    public TestException2() {  
    }  
  
    @SuppressWarnings("finally")
    boolean testEx() throws Exception {  
        boolean ret = true;  
        try {  
           throw new Exception();
        } catch (Exception e) {  
            System.out.println("testEx, catch exception");  
            ret = false;  
            throw e;  
        } finally {  
            System.out.println("testEx, finally; return value=" + ret);  
            return ret;  
        }  
    }  
    public static void main(String[] args) {  
        TestException2 testException1 = new TestException2();  
        try {  
            testException1.testEx();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}

 控制檯輸出:

testEx, catch exception

testEx, finally; return value=false

 

如果將testEx中finally字句的return註釋掉,該方法會拋出異常給main方法。

結論:如果catch到異常會執行catch子句,在返回return或throw之前會執行finally子句,如果finally子句存在return或throw會優先執行。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章