-4

以下代码给出了所需的输出,即“发生算术异常”

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"

谁能解释一下?

4

1 回答 1

0

对于这条线

a[10] = 30/0; 

一旦30/0被评估,就会抛出异常。

在任何时候,代码都可以抛出单个异常。即使您捕获了异常及其基类,您也可以运行单个 catch 语句。

于 2021-06-02T06:49:44.550 回答