try
塊也可以有零個或一個finally
塊。 finally
塊總是與try
塊一起使用。
finally
塊的語法是:
finally {
// Code for finally block
}
finally
塊以關鍵字finally
開始,後面緊跟一個大括號和一個大括號。finally
塊的程式碼放在大括號內。
try
,catch
和finally
塊有兩種可能的組合:try-catch-finally
或try-finally
。try
塊可以後跟零個或多個catch
塊。try
塊最多可以有一個finally
塊。try
塊必須有一個catch
塊和一個finally
塊或兩者都有。try-catch-finally
塊的語法是:
try {
// Code for try block
}
catch(Exception1 e1) {
// Code for catch block
}
finally {
// Code for finally block
}
try-finally
塊的語法是:
try {
// Code for try block
}
finally {
// Code for finally block
}
無論在相關聯的try
塊和/或catch
塊中發生什麼,finally
塊中的程式碼都保證執行。所以,一般使用finally
塊來寫清理程式碼。
例如,可能用來釋放一些資源,如資料庫連線的關閉,檔案的關閉等,當完成它們時,必須釋放。
在try-finally
塊允許實現這個邏輯。程式碼結構將如下所示:
try {
// Obtain and use some resources here
}
finally {
// Release the resources that were obtained in the try block
}
下面的程式碼演示了finally
塊的使用。
public class Main {
public static void main(String[] args) {
int x = 10, y = 0, z = 0;
try {
System.out.println("Before dividing x by y.");
z = x / y;
System.out.println("After dividing x by y.");
} catch (ArithmeticException e) {
System.out.println("Inside catch block a.");
} finally {
System.out.println("Inside finally block a.");
}
try {
System.out.println("Before setting z to 2.");
z = 2;
System.out.println("After setting z to 2.");
}
catch (Exception e) {
System.out.println("Inside catch block b.");
} finally {
System.out.println("Inside finally block b.");
}
try {
System.out.println("Inside try block c.");
}
finally {
System.out.println("Inside finally block c.");
}
try {
System.out.println("Before executing System.exit().");
System.exit(0);
System.out.println("After executing System.exit().");
} finally {
// This finally block will not be executed
// because application exits in try block
System.out.println("Inside finally block d.");
}
}
}
上面的程式碼生成以下結果。
Before dividing x by y.
Inside catch block a.
Inside finally block a.
Before setting z to 2.
After setting z to 2.
Inside finally block b.
Inside try block c.
Inside finally block c.
Before executing System.exit().
捕獲的異常可以被重新丟擲。
public class Main {
public static void main(String[] args) {
try {
m1();
} catch (MyException e) {
// Print the stack trace
e.printStackTrace();
}
}
public static void m1() throws MyException {
try {
m2();
} catch (MyException e) {
e.fillInStackTrace();
throw e;
}
}
public static void m2() throws MyException {
throw new MyException("An error has occurred.");
}
}
class MyException extends Exception {
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(Throwable cause) {
super(cause);
}
}
上面的程式碼生成以下結果。
MyException: An error has occurred.
at Main.m1(Main.java:14)
at Main.main(Main.java:4)