为什么try-catch没有给出所需的输出



下面的代码给出了所需的输出;发生算术异常";

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语句。

最新更新