尝试打印多个catch语句

时间:2020-01-01 13:38:43

标签: java exception try-catch

在下面的代码中,我试图打印多个catch语句,但是我只得到一个。据我了解,顺序是优先的,即将打印第一个catch语句匹配项。但是我想打印两个相关的陈述。有什么办法吗?

    class Example2{
    public static void main(String args[]){
     try{
         int a[]=new int[7];
         a[10]=30/0;
         System.out.println("First print statement in try block");
     }
     catch(ArithmeticException e){
        System.out.println("Warning: ArithmeticException");
     }
     catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Warning: ArrayIndexOutOfBoundsException");
     }
     catch(Exception e){
        System.out.println("Warning: Some Other exception");
     }
   System.out.println("Out of try-catch block...");
  }
}

我希望同时打印边界和算术语句。有什么办法吗?

4 个答案:

答案 0 :(得分:3)

这里的问题不是catch块的优先级。首先,您尝试划分30/0,并生成ArithmeticException。不会生成ArrayIndexOutOfBounds异常,因为永远不会有任何值可供您尝试分配给a[10]

答案 1 :(得分:1)

一个异常仅与一个catch块匹配。

答案 2 :(得分:0)

您需要合并这些catch语句,因为只有一个会被触发

class Example2{
public void main(String args[]){
    try{
        int a[]=new int[7];
        a[10]=30/0;
        System.out.println("First print statement in try block");
    } catch(ArithmeticException | ArrayIndexOutOfBoundsException  e) {

    }
    System.out.println("Out of try-catch block...");
}

}

然后在catck块中可以处理异常。

答案 3 :(得分:0)

有一种使用嵌套的try语句来打印两个异常的方法,如下所示。否则,不必打印所有例外。

class ExceptionHandling{
    public static void main(String[] args){
        try{
            try{
                String s=null;
                System.out.println(s.length());
            }
            
            catch(NullPointerException e){
                System.out.println(e);
            }   
            
            int a=4/0;
        }
        catch(ArithmeticException e){
            System.out.println(e);
        }
    }
}