【发布时间】:2019-10-29 03:59:48
【问题描述】:
让我们参考下一段代码:
try{
/*Code that may throw IndexOutOfBoundsException or ArrayIndexOut......*/
} catch (IndexOutOfBoundsException e){
/*handle*/
} catch (ArrayIndexOutOfBoundsException e){
/*handle*/
}
为什么不编译,但如果切换 catch 子句的顺序,它会编译?
也许我必须先写一个特定的异常,然后再写一个更一般的异常?
【问题讨论】:
-
IndexOutOfBoundsException是ArrayIndexOutOfBoundsException的父级,因此永远不会调用另一个 catch。 -
首先需要捕获更具体的异常。
-
我认为您不太可能需要不同的处理方式,那么为什么不直接捕获
IndexOutOfBoundsException并在一个捕获块中同时处理两者?