finally是必須執行的語句塊,即便try或者catch有返回。但是測試過其實try或者catch裏面的return是先執行的,只是結果緩存了,沒有跳轉,而是到了finally語句塊。
來兩段代碼記錄下
public class App
{
public static void main( String[] args )
{
System.out.println("P2: " + new App().test());
}
public int test() {
int i = -5;
int j = 0;
try {
throw new Exception("xx");
} catch (Exception e) {
return j++;
} finally {
System.out.println("P1: " + i + " " + j);
}
}
}
// 輸出
P1: -5 1
P2: 0
j++運行了,返回值是0暫存在方法棧中,然後強制跳轉到finally,此時j已加1。輸出P1,結束finally後,如果finally裏面沒有return,則原catch返回0。
當然如果try或者catch裏面有system.exit(0);會直接退出,不進入finally
public class App
{
public static void main( String[] args )
{
System.out.println("P2: " + new App().test());
}
public int test() {
int i = -5;
int j = 0;
try {
return i++;
// throw new Exception("xx");
} catch (Exception e) {
return j++;
} finally {
System.out.println("P1: " + i + " " + j);
}
}
}
// 輸出
P1: -4 0
P2: -5
類似