在 Java 中,我們可以在另一個 try catch 塊內宣告 try catch 塊嗎?
是的,我們可以在另一個 try-catch 塊內宣告一個 try-catch 塊,這稱為巢狀 try-catch 塊。
巢狀 Try-Catch 塊
- 如果內部 try 語句沒有為特定異常提供匹配的 catch 語句,則控制權將傳遞到下一個 try 語句的 catch 處理程式,這些處理程式期望有匹配的 catch 語句。
- 這種情況將持續,直到其中一個 catch 語句成功,或者直到所有巢狀 try 語句都完成。
- 如果沒有任何 catch 語句匹配,則 Java 執行時系統將處理該異常。
- 當使用巢狀 try 塊時,內部 try 塊首先執行。內部 try 塊中丟擲的任何異常都將在相應的 catch 塊中捕獲。如果找不到匹配的 catch 塊,則會檢查外部 try 塊的 catch 塊,直到所有巢狀 try 語句都耗盡。如果找不到匹配的塊,則 Java 執行時環境將處理執行。
語法
try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { // catch the corresponding exception } } catch(Exception e) { // catch the corresponding exception } .............
示例
import java.io.*; public class NestedTryCatchTest { public static void main (String args[]) throws IOException { int n = 10, result = 0; try { // outer try block FileInputStream fis = null; fis = new FileInputStream (new File (args[0])); try { // inner trty block result = n/0; System.out.println("The result is"+result); } catch(ArithmeticException e) { // inner catch block System.out.println("Division by Zero"); } } catch (FileNotFoundException e) { // outer catch block System.out.println("File was not found"); } catch(ArrayIndexOutOfBoundsException e) { // outer catch block System.out.println("Array Index Out Of Bounds Exception occured "); } catch(Exception e) { // outer catch block System.out.println("Exception occured"+e); } } }
輸出
Array Index Out Of Bounds Exception occured
廣告