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会优先执行。