在 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

更新于: 2019-07-30

9K+ 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.