W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
?try
?塊也可以有零個或一個? finally
? 塊。 ?finally
?塊總是與 ?try
?塊一起使用。
使用 ?finally
? 塊的語法是
finally {
// Code for finally block
}
?finally
? 塊以關(guān)鍵字 ?finally
? 開始,后面緊跟一對大括號。
?finally
? 塊的代碼放在大括號內(nèi)。
?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
}
無論在相關(guān)聯(lián)的? try
?和 ?/
? 或 ?catch
? 塊中發(fā)生什么,?finally
?塊都被保證被執(zhí)行。
通常,我們使用 ?finally
? 塊來寫清理代碼。
例如,我們可能獲得一些資源,當(dāng)我們完成它們時,必須釋放。
?try - finally
? 塊允許你實現(xiàn)這個邏輯。
您的代碼結(jié)構(gòu)將如下所示:
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.");
}
}
}
上面的代碼生成以下結(jié)果。
捕獲的異??梢灾匦乱谩?/p>
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);
}
}
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: