@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是否一定會執(zhí)行
try語句無論是 throw exception 或者 return僧凰,finally語句都會被執(zhí)行厌衔,但有幾個情況例外:
- try之前的語句打斷了程序的執(zhí)行矗烛,導(dǎo)致try語句沒有執(zhí)行,那finally自然無法執(zhí)行
- try或者catch語句執(zhí)行執(zhí)行了
system.exit(0)
,導(dǎo)致虛擬機(jī)退出则涯,finally無法執(zhí)行
finally的執(zhí)行時機(jī)
- finally在 return 或者throw exception 前執(zhí)行
- 對于return語句finally會保留return的狀態(tài)(復(fù)制一份),即使在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());
}
輸出結(jié)果
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();
}
}