为什么 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 语句。