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會優先執行。