【问题标题】:Trying to print multiple catch statements尝试打印多个 catch 语句
【发布时间】:2020-01-01 13:38:43
【问题描述】:

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

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

【问题讨论】:

  • 我不这么认为。您将只能获得其中之一。
  • 代码将在ArithmeticException ArrayIndexOutOfBoundsException 上失败,不会在两者上都失败。
  • 这样想:如果“发生了一些异常”,为什么代码会继续执行(并且可能会得到另一个“异常”)?它会立即尝试处理第一个异常。

标签: java exception try-catch


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    一个异常只匹配一个 catch 块。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 但是,归根结底,e 要么是 ArithmeticException 要么是 ArrayIndexOutOfBoundsException,当然不是两者兼而有之。根据发布的代码,它将始终是ArithmeticException
      • 是的,存档小船异常的唯一方法是将它们放入多个 try 块中。
      • 你是什么意思存档两个例外的唯一方法?总是只会处理一个异常。这就是我对之前评论的观点:您发布的语法(或任何其他语法)不会改变只有其中一个会被捕获的事实。
      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-13
        • 2012-05-22
        • 1970-01-01
        • 2016-03-05
        • 1970-01-01
        • 2014-12-22
        • 2010-10-29
        相关资源
        最近更新 更多