为什么必须先捕获ArrayIndexOutOfBoundsException然后再捕获IndexOutOfBoundsException?

use*_*035 2 java exception

让我们以下面的代码为参考:

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

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

lea*_*iro 5

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

因此,如果有一个ArrayIndexOutOfBoundsExceptionIndexOutOfBoundsException:匹配的话,换句话说,捕获ArrayIndexOutOfBoundsException将是无法实现的。

For all exceptions declared in your catches to be reachable, you need to order them from the most specific to the most generic ones.