【问题标题】:Why is necessary to first catch ArrayIndexOutOfBoundsException and then IndexOutOfBoundsException? [duplicate]为什么要先捕获 ArrayIndexOutOfBoundsException 再捕获 IndexOutOfBoundsException? [复制]
【发布时间】:2019-10-29 03:59:48
【问题描述】:

让我们参考下一段代码:

try{
   /*Code that may throw IndexOutOfBoundsException or ArrayIndexOut......*/
} catch (IndexOutOfBoundsException e){
    /*handle*/
} catch (ArrayIndexOutOfBoundsException e){
    /*handle*/
}
  • 为什么不编译,但如果切换 catch 子句的顺序,它会编译?

  • 也许我必须先写一个特定的异常,然后再写一个更一般的异常?

【问题讨论】:

  • IndexOutOfBoundsExceptionArrayIndexOutOfBoundsException 的父级,因此永远不会调用另一个 catch。
  • 首先需要捕获更具体的异常。
  • 我认为您不太可能需要不同的处理方式,那么为什么不直接捕获 IndexOutOfBoundsException 并在一个捕获块中同时处理两者?

标签: java exception


【解决方案1】:

因为ArrayIndexOutOfBoundsException 扩展自IndexOutOfBoundsException,这意味着第一个比第二个更具体。

因此,如果有一个 ArrayIndexOutOfBoundsException,它将与 IndexOutOfBoundsException 匹配:换句话说,ArrayIndexOutOfBoundsException 的捕获将无法访问。

要使您在catches 中声明的所有异常都可以访问,您需要将它们从最具体的到最通用的排序。

【讨论】:

    【解决方案2】:

    因为ArrayIndexOutOfBoundsExceptionIndexOutOfBoundsException 的子类,所以第二个子句是不可达的,因为第一个子句总是会捕获异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2013-01-25
      • 1970-01-01
      • 2015-11-28
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多