简体   繁体   English

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

[英]Why try-catch is not giving the desired output?

The following code gives the desired output which is "Arithmetic Exception occurs"以下代码给出了所需的 output 即“发生算术异常”

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");
}

but if I want to get two exceptions at a time, the modified code will be但如果我想一次得到两个异常,修改后的代码将是

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");
}

but instead of giving both, "Arithmetic Exception occurs" & "ArrayIndexOutOfBounds Exception occurs" the output is only "Arithmetic Exception occurs"但不是同时给出"Arithmetic Exception occurs" & "ArrayIndexOutOfBounds Exception occurs" ,output 只是"Arithmetic Exception occurs"

Can anyone explain this?谁能解释一下?

For this line对于这条线

a[10] = 30/0; 

As soon as 30/0 is evaluated, exception is thrown.一旦评估30/0 ,就会引发异常。

At any point, the code can throw single exception.在任何时候,代码都可以抛出单个异常。 Even if you catch on the exception and its base class, you can run single catch statement.即使您捕捉到异常及其基础 class,您也可以运行单个 catch 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM