能否在一个catch块中捕获多个Java异常?
异常是在程序执行期间发生的错误(*运行时错误*)。当发生异常时,程序会突然终止,异常行之后的代码将不会执行。
代码中的多个异常
在Java 7之前,如果代码可能产生多个异常,并且需要分别处理它们,则必须在单个try块上使用多个catch块。
示例
下面的Java程序包含一个数字数组(已显示)。它从用户那里接收数组中的两个位置,并将第一个位置的数字除以第二个位置的数字。
输入值时:
如果选择的位置不在显示的数组中,则会抛出ArrayIndexOutOfBoundsException异常。
- 如果选择0作为分母,则会抛出ArithmeticException异常。
在这个程序中,我们使用两个不同的catch块处理了所有可能的异常。
import java.util.Arrays; import java.util.Scanner; public class MultipleCatchBlocks { public static void main(String [] args) { Scanner sc = new Scanner(System.in); int[] arr = {10, 20, 30, 2, 0, 8}; System.out.println("Enter 3 integer values one by one: "); 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 e) { System.out.println("Warning: You have chosen a position which is not in the array"); } catch(ArithmeticException e) { System.out.println("Warning: You cannot divide a number with 0"); } } }
输出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) 2 8 Warning: You have chosen a position which is not in the array
输出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) 1 4 Warning: You cannot divide a number with 0
多重catch块
从Java 7开始,引入了多重catch块,可以使用它在一个catch块中处理多个异常。
在这种情况下,需要使用“|”分隔要处理的所有异常类,如下所示:
catch(ArrayIndexOutOfBoundsException | ArithmeticException exp) { System.out.println("Warning: Enter inputs as per instructions "); }
示例
下面的Java程序演示了多重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("Enter 3 integer values one by one: "); 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
广告