Java 程式設計/關鍵字/finally
外觀
finally 是一個關鍵字,它是 try 塊的可選結尾部分。
程式碼部分 1: try 塊。
try {
// ...
} catch (MyException1 e) {
// Handle the Exception1 here
} catch (MyException2 e) {
// Handle the Exception2 here
} finally {
// This will always be executed no matter what happens
}
|
finally 塊中的程式碼將始終執行。即使在 try 塊中存在異常或執行 return 語句,這種情況也是如此。
try 塊中可能發生三種情況。首先,沒有丟擲異常
|
|
您可以看到我們已透過 try 塊,然後我們已執行 finally 塊,並已繼續執行。現在,丟擲了一個捕獲的異常:|
程式碼部分 3: 丟擲了一個捕獲的異常。
System.out.println("Before the try block");
try {
System.out.println("Enter inside the try block");
throw new MyException1();
System.out.println("Terminate the try block");
} catch (MyException1 e) {
System.out.println("Handle the Exception1");
} catch (MyException2 e) {
System.out.println("Handle the Exception2");
} finally {
System.out.println("Execute the finally block");
}
System.out.println("Continue");
|
程式碼部分 3 的控制檯
Before the try block Enter inside the try block Handle the Exception1 Execute the finally block Continue |
我們已透過 try 塊,直到發生異常的位置,然後我們已執行匹配的 catch 塊、finally 塊,並已繼續執行。現在,丟擲了一個未捕獲的異常
程式碼部分 4: 丟擲了一個未捕獲的異常。
System.out.println("Before the try block");
try {
System.out.println("Enter inside the try block");
throw new Exception();
System.out.println("Terminate the try block");
} catch (MyException1 e) {
System.out.println("Handle the Exception1");
} catch (MyException2 e) {
System.out.println("Handle the Exception2");
} finally {
System.out.println("Execute the finally block");
}
System.out.println("Continue");
|
程式碼部分 4 的控制檯
Before the try block Enter inside the try block Execute the finally block |
我們已透過 try 塊,直到發生異常的位置,並已執行 finally 塊。沒有程式碼在 try-catch 塊之後執行。如果在 try-catch 塊之前發生異常,則不會執行 finally 塊。
如果在 finally 中使用 return 語句,它將覆蓋 try-catch 塊中的 return 語句。例如,結構
程式碼部分 5: Return 語句。
try {
return 11;
} finally {
return 12;
}
|
將返回 12,而不是 11。專業的程式碼幾乎不包含更改執行順序的語句(如 return、break、continue)在 finally 塊中,因為這樣的程式碼更難閱讀和維護。
另請參閱