先看兩段代碼,請試着分别寫出它們的輸出結果。
1、try-catch 塊與 finally 塊同時抛異常。
import java.io.IOException;
public class ExceptionInFinallyBlock {
public static void main(String[] args) {
try {
try {
System.out.print("A");
throw new Exception("1");
} catch(Exception e) {
System.out.print("B");
throw new Exception("2");
} finally {
System.out.print("C");
throw new IOException("3");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
2、try-catch 塊與 finally 塊同時包含 return 語句。
public class ReturnStatementInFinallyBlockTest {
public static void main(String[] args) {
System.out.println(getReturnValue());
}
public static int getReturnValue() {
try {
System.out.print("A");
return 1;
} finally {
System.out.print("C");
return 2;
}
}
}
Java标準文檔中給出了詳細的描述,可以用一句話簡單概括上面兩個示例執行邏輯:
- 在 finally 塊中抛出的任何異常都會覆寫掉在其前面由 try 或者 catch 塊抛出異常。包含 return 語句的情形相似。
鑒于此,除必要情況下,應該盡量避免在 finally 塊中抛異常或者包含 return 語句。
PS: 實際上,當你把上面兩段代碼拷貝到 eclipse,會收到 eclipse 的 warning: finally block does not complete normally。
----------------
輸出結果:
1、ABC3
2、AC2
本文總結自:SO