[英]Java: Hypothetical question about finally block
如果您在finally塊中拋出錯誤會怎樣? 是否在相應的catch子句之一中進行處理?
僅當您在finally塊中放置另一個try-catch塊時。 否則,就像其他任何錯誤一樣。
它不會處理異常,直到它被夾在最終阻止它的自我。
public static void main(String[] args) throws Exception {
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
throw new Exception();
}
}
上面的代碼將引發異常,但是如果您執行以下操作,它將起作用:
public static void main(String[] args){
try {
System.out.println("In try");
} catch (Exception e) {
System.out.println("In catch");
} finally{
try{
throw new Exception();
}catch(Exception e){}
}
}
您需要在finally或catch塊內包括try-catch塊。
例如:
try {
// your code here
} finally {
try {
// if the code in finally can throw another exception, you need to catch it inside it
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
} catch (Exception e) {
try {
// your error handling routine here
} catch (Exception e) {
// probably not much to do besides telling why it failed
}
}
不。 它會被一個catch捕獲,然后將整個try / catch / finally嵌套在另一個try / catch中。 否則,異常將被拋出該函數,並由該函數的調用者處理。
不,不是。 您將不得不在finally塊中進行處理,或者在方法描述中定義適當的throw聲明。
不,catch塊只能捕獲在相應try
塊內拋出的異常-不能是finally
塊。 (當然,如果該finally
塊在另一個try
塊內,則仍使用該 try
塊的catch子句。)
JLS中的相關部分是14.20.2 。 那里列出的每個流都有這樣的東西:
如果finally塊由於某種原因突然完成,則try語句由於相同的原因突然完成。
換句話說,沒有任何與finally
塊關聯的catch
子句嘗試處理該異常。
執行的順序通常由以下語句的順序直接指示:1. try,2.以指定的順序捕獲異常(僅執行一次catch),3.最后。
因此,當執行finally塊時(請注意,即使在try或catch塊中引發return語句或異常的情況下,情況總是如此),try語句的執行處於最后階段,因此無法捕獲其他可拋物。 如前所述,必須在堆棧下方(或上方,取決於視點;))處處理異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.