Java的finally调用机制测试
测试结论:
- finally会在后续代码之前进行调用
- finally在Catch中向外丢出Exception之后也会执行,而函数后续代码在Exception丢出之后不会执行
测试代码Throw
public void someMethod() throws Exception {
System.out.print("Execute Before\n");
try {
System.out.print("Execute Try\n");
int i = 1/0;
} catch (Exception e) {
System.out.print("Execute Catch\n");
throw e;
} finally {
System.out.print("Execute Finally\n");
}
System.out.print("Execute After\n");
}
测试输出Throw
Execute Before
Execute Try
Execute Catch
Execute Finally
测试代码Not Throw
public void someMethod() throws Exception {
System.out.print("Execute Before\n");
try {
System.out.print("Execute Try\n");
int i = 1/0;
} catch (Exception e) {
System.out.print("Execute Catch\n");
} finally {
System.out.print("Execute Finally\n");
}
System.out.print("Execute After\n");
}
测试输出Not Throw
Execute Before
Execute Try
Execute Catch
Execute Finally
Execute After