【问题标题】:How can I catch multiple exceptions at the same time? [duplicate]如何同时捕获多个异常? [复制]
【发布时间】:2021-09-09 19:45:45
【问题描述】:

我试图捕获多个异常,但我不能。我只能捕获一个异常。

class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[10];
      array[10] = 30 / 0;
    } catch (ArithmeticException e) {
      System.out.println(e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    }
  }
}

【问题讨论】:

  • docs.oracle.com/javase/7/docs/technotes/guides/language/… 这已经存在一段时间了;搜索网络也可以。
  • 什么多重例外?当发生被零除错误时,try 块中的代码将停止执​​行,因此它永远不会到达会导致索引越界错误的代码。
  • 一次只能有一个异常,不超过这个,因为当异常发生时它会移动到catch块

标签: java exception


【解决方案1】:

正如在语句array[10] = 30 / 0; 中一样,您可以看到编译器将首先执行的是对 30 除以零的求值,这肯定会引发算术异常。由于分配操作之前的语句会抛出异常,因此它将从 try 块中断并跳到 catch (ArithmeticException e) 块,array[invalidIndex] 永远不会执行,因此它永远不会抛出 ArrayIndexOutOfBoundsException

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 2013-01-31
    • 2016-08-14
    • 2013-03-17
    • 2016-05-28
    • 2020-05-10
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多