问题描述
public static void main(String[] args) {
try {
int []a = new int[5];
a[5] = 30/0;
} catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch(Arrayindexoutofboundsexception e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch(Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
public static void main(String[] args) {
try {
int []a = new int[5];
a[10] = 30/0;
} catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch(Arrayindexoutofboundsexception e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch(Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
但不是同时提供,"Arithmetic Exception occurs" & "ArrayIndexOutOfBounds Exception occurs"
的输出仅为 "Arithmetic Exception occurs"
谁能解释一下?
解决方法
对于这一行
a[10] = 30/0;
一旦对 30/0
求值,就会抛出异常。
在任何时候,代码都可以抛出单个异常。即使您捕获异常及其基类,您也可以运行单个 catch 语句。