简体   繁体   English

尝试打印多个 catch 语句

[英]Trying to print multiple catch statements

In the following code, I am trying to print multiple catch statements but I am getting only one.在下面的代码中,我试图打印多个 catch 语句,但我只得到一个。 As far as I understand that the order is prioritized ie the first catch statement matching will be printed.据我了解,顺序是优先的,即第一个 catch 语句匹配将被打印。 But I want to print both relevant statements.但我想打印两个相关声明。 is there any way for this?有什么办法吗?

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

I want both, out of bound and arithmetic statements to be printed.我想要打印出界外和算术语句。 Is there any way?有什么办法吗?

The issue here isn't prioritization of the catch blocks.这里的问题不是catch块的优先级。 First, you attempt to divide 30/0 , and generate an ArithmeticException .首先,您尝试除以30/0并生成ArithmeticException The ArrayIndexOutOfBounds exception will never be generated because there's never a value for you to try to assign to a[10] .永远不会生成ArrayIndexOutOfBounds异常,因为您永远不会尝试分配给a[10]

异常只匹配一个 catch 块。

You need to merge those catch statements, because only one is fired at a你需要合并那些 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...");
    }
}

And in the catck block, you can then work with the exception.然后在 catck 块中,您可以处理异常。

There is one way to print both the exceptions by using nested try statements as shown below.有一种方法可以使用嵌套的 try 语句打印这两个异常,如下所示。 Otherwise, it should not be necessary to print all the exceptions.否则,就没有必要打印所有异常。

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

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

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