繁体   English   中英

尝试打印多个 catch 语句

[英]Trying to print multiple catch statements

在下面的代码中,我试图打印多个 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...");
  }
}

我想要打印出界外和算术语句。 有什么办法吗?

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

异常只匹配一个 catch 块。

你需要合并那些 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 块中,您可以处理异常。

有一种方法可以使用嵌套的 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);
        }
    }
}

暂无
暂无

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

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