Java 中的多重捕获
java 8object oriented programmingprogramming更新于 2025/11/7 3:56:17
异常是指程序执行过程中发生的问题(运行时错误)。发生异常时,程序会突然终止,并且生成异常的代码行之后的代码将永远不会执行。
代码中的多个异常
在 Java 7 之前,每当代码可能生成多个异常时,如果需要专门处理这些异常,则应该在单个 try 中使用多个 catch 块。
多重捕获块
从 Java 7 开始,引入了多重捕获块,您可以使用该块在单个 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

