一个 try 块后面可以跟多个 catch 块。多个 catch 块的语法如下所示 -

语法

try {
   // 受保护的代码
} catch (ExceptionType1 e1) {
   // 捕获块
} catch (ExceptionType2 e2) {
   // 捕获块
} catch (ExceptionType3 e3) {
   // 捕获块
} 

前面的语句演示了三个 catch 块,但一次尝试后可以拥有任意数量的 catch 块。如果受保护的代码中发生异常,则该异常将被抛出到列表中的第一个 catch 块。如果抛出的异常的数据类型与 ExceptionType1 匹配,则会在那里捕获该异常。如果不是,则异常将传递到第二个 catch 语句。这种情况一直持续到异常被捕获或通过所有捕获,在这种情况下,当前方法停止执行,并且异常被抛出到调用堆栈上的前一个方法。

要记住的要点

  • 一次只能处理一种类型的异常。在 protected 中,只会引发一种类型的异常,因此只会在相关的 catch 块中进行处理。

  • catch 块的顺序非常重要。顺序应该是从特定例外到一般例外。如果父异常块出现在子异常块之前,编译器将抱怨并抛出编译时错误。

示例 1

这里是代码显示如何使用多个 try/catch 语句的段。在此示例中,我们通过将值除以 0 来创建错误。由于它不是 ArrayIndexOutOfBoundsException,因此下一个 catch 块会处理异常并打印详细信息。

package com.yxjc123;

public class ExcepTest {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         int b = 0;
         int c = 1/b;
         System.out.println("Access element three :" + a[3]);
      }
      catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("ArrayIndexOutOfBoundsException thrown  :" + e);
      }catch (Exception e) {
          System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
} 

输出

Exception thrown  :java.lang.ArithmeticException: / by zero
Out of the block 

示例 2

在此代码段中,我们将展示如何使用多个 try/catch 语句的另一个示例。在此示例中,我们通过将值除以 0 并使用 ArithmeticException 处理它来创建错误。

package com.yxjc123;

public class ExcepTest {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         int b = 0;
         int c = 1/b;
         System.out.println("Access element three :" + a[3]);
      }
      catch (ArithmeticException e) {
         System.out.println("ArithmeticException thrown  :" + e);
      }
      catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("ArrayIndexOutOfBoundsException thrown  :" + e);
      }catch (Exception e) {
          System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
} 

输出

ArithmeticException thrown  :java.lang.ArithmeticException: / by zero
Out of the block 

捕获多种类型的异常

从 Java 7 开始,您可以使用单个 catch 块处理多个异常,这一功能简化了代码。以下是具体操作方法 -

catch (IOException|FileNotFoundException ex) {
   logger.log(ex);
   throw ex; 

示例 3

这里的代码段显示了如何在单个语句中使用多个 catch。在此示例中,我们通过将值除以 0 来创建错误。在单个语句中,我们处理 ArrayIndexOutOfBoundsException 和 ArithmeticException。

package com.yxjc123;

public class ExcepTest {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         int b = 0;
         int c = 1/b;
         System.out.println("Access element three :" + a[3]);
      }
      catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
} 

输出

Exception thrown  :java.lang.ArithmeticException: / by zero
Out of the block