[英]will the nested try exception be caught by outer catch block
我有類似的東西
try{
try{ . .a method call throwing a exception..}
finally { ...}
} catch()...
方法調用和外部catch(類型參數)拋出的異常類型是相同的。
嵌套的try異常是否會被外部catch塊捕獲?
相關規則在Java語言規范14.20.2中。 執行try-finally和try-catch-finally
內部try
塊中的異常V
的結果將取決於finally
塊的完成方式。 如果它正常完成,則try-finally
將由於V而突然完成。如果finally
塊由於某種原因而突然完成R
則則try-finally
由於R
而突然完成,並且V
被丟棄。
這是一個展示這個的程序:
public class Test {
public static void main(String[] args) {
try {
try {
throw new Exception("First exception");
} finally {
System.out.println("Normal completion finally block");
}
} catch (Exception e) {
System.out.println("In first outer catch, catching " + e);
}
try {
try {
throw new Exception("Second exception");
} finally {
System.out.println("finally block with exception");
throw new Exception("Third exception");
}
} catch (Exception e) {
System.out.println("In second outer catch, catching " + e);
}
}
}
輸出:
Normal completion finally block
In first outer catch, catching java.lang.Exception: First exception
finally block with exception
In second outer catch, catching java.lang.Exception: Third exception
由於第二個finally
區塊的突然完成,第二個外部捕獲沒有看到“第二個例外”。
盡量減少finally
塊突然完成的風險。 處理其中的任何異常,以便它將正常完成,除非它們對整個程序是致命的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.