@Test
public void testFinally(){
//statement...
try {
System.out.println("start");
throw new RuntimeException("测试");
}catch (Exception e){
System.out.println("exception");
}finally {
System.out.println("finally");
}
}
finally是否一定会执行
try语句无论是 throw exception 或者 return,finally语句都会被执行,但有几个情况例外:
- try之前的语句打断了程序的执行,导致try语句没有执行,那finally自然无法执行
- try或者catch语句执行执行了
system.exit(0)
,导致虚拟机退出,finally无法执行
finally的执行时机
- finally在 return 或者throw exception 前执行
- 对于return语句finally会保留return的状态(复制一份),即使在finally中改变了return变量的值,仍然会返回之前的return值。
@Test
public int testFinally(){
int res = 10;
try {
System.out.println("start");
//Assert.isNull(1);
//throw new RuntimeException("测试");
return res;
}catch (Exception e){
System.out.println("exception");
e.printStackTrace();
return 0;
}finally {
System.out.println("finally");
res = 99;
}
}
@Test
public void test(){
System.out.println(testFinally());
}
输出结果
start
finally
10
可以省略catch语句try...finally...
@Test
public void testFinally() {
Lock lock = new ReentrantLock();
try {
//加锁
lock.lock();
System.out.println("try");
throw new RuntimeException("测试");
} /*catch (Exception e) {
//忽略catch,有异常自动抛出
}*/ finally {
System.out.println("finally");
//放在finally中以保证在任何情况下退出都能解锁
lock.unlock();
}
}