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

Java 为什么必须先捕获ArrayIndexOutOfBoundsException,然后再捕获IndexOutOfBoundsException?,java,exception,Java,Exception,让我们参考下一个代码: try{ /*Code that may throw IndexOutOfBoundsException or ArrayIndexOut......*/ } catch (IndexOutOfBoundsException e){ /*handle*/ } catch (ArrayIndexOutOfBoundsException e){ /*handle*/ } 为什么这个不编译,但是如果一个开关编译了catch子句的序列呢 也许我必须先写一

让我们参考下一个代码:

try{
   /*Code that may throw IndexOutOfBoundsException or ArrayIndexOut......*/
} catch (IndexOutOfBoundsException e){
    /*handle*/
} catch (ArrayIndexOutOfBoundsException e){
    /*handle*/
}
  • 为什么这个不编译,但是如果一个开关编译了catch子句的序列呢

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

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


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


    要访问
    catch
    es中声明的所有异常,您需要从最具体的异常到最一般的异常进行排序。

    因为
    ArrayIndexOutOfBoundsException
    IndexOutOfBoundsException
    的子类,因此,第二个子句是不可访问的,因为第一个子句将始终捕获异常。

    IndexOutOfBoundsException
    ArrayIndexOutOfBoundsException
    的父级,因此将永远不会调用其他捕获。第一个子句需要捕获更具体的异常。我认为您不太可能需要不同的处理,那么,为什么不在一个catch块中捕获
    IndexOutOfBoundsException
    并处理这两个问题呢?