Java多捕获

例外是在程序执行期间发生的问题(运行时错误)。当发生异常时,程序会突然终止,并且生成异常的行之后的代码将永远不会执行。

代码中有多个异常

在Java 7之前,只要我们有一个可能生成多个异常的代码,并且如果您需要专门处理它们,则应该一次尝试使用多个catch块。

多捕获块

从Java 7开始,使用此功能引入了Multi-catch块,您可以在单个catch块中处理多个异常。

在此,您需要指定所有要处理的异常类,并用“ | |”分隔。”,如下所示-

catch(ArrayIndexOutOfBoundsException | ArithmeticException exp) {
   System.out.println("Warning: Enter inputs as per instructions ");
}

示例

以下Java程序演示了Multi-catch的用法。在这里,我们在单个catch块中处理所有异常。

import java.util.Arrays;
import java.util.Scanner;
public class MultiCatch {
   public static void main(String [] args) {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array, (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }
      catch(ArrayIndexOutOfBoundsException | ArithmeticException exp) {
         System.out.println("Warning: Enter inputs as per instructions ");
      }
   }
}

输出1

Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array, (enter positions 0 to 5)
0
9
Warning: Enter inputs as per instructions

输出2

Enter 3 integer values one by one:
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator (not 0) from this array, (enter positions 0 to 5)
2
4
Warning: Enter inputs as per instructions