捕获java.lang.ArrayIndexOutOfBoundsException

时间:2016-02-21 08:21:03

标签: java exception-handling

我是Java新手。任何人都可以帮我解释一下,为什么catch没有捕获MyException(它扩展了ArrayIndexOutOfBoundsException)? 我的例子:

public class TestClass {
    public static void main(String[] args) {
        try{
            doTest();
        }
        catch(MyException me){
            System.out.println("MyException is here");
        }
    }

    static void doTest() throws MyException{
        int[] array = new int[10];
        array[10] = 1000;

    }


}
class MyException extends ArrayIndexOutOfBoundsException {
    public MyException(String msg){
     super(msg);
    }
}

结果是: “线程中的异常”主“java.lang.ArrayIndexOutOfBoundsException:10位于TestClass.doTest(TestClass.java:14)的TestClass.main(TestClass.java:5)”

为什么不是“MyException在这里”?

3 个答案:

答案 0 :(得分:3)

您的方法实际上仅抛出blockquote { position:absolute; width:75px; height:75px; border-radius:50%; background-color:#000; color:#fff; left:45%; top:#45% }

你抓住了ArrayIndexOutOfBoundsException,但这不是被抛出的东西,所以MyException子句没有效果。

如果你想抛出catch,你必须修改方法以捕捉MyException并抛出ArrayIndexOutOfBoundsException

答案 1 :(得分:1)

您的doTest方法不会抛出自定义异常。要抛出异常,请使用

throw new MyException("your message");

答案 2 :(得分:1)

你混淆了subtype-supertype-relationship。

该代码会引发ArrayIndexOutOfBoundsException而不是MyException。捕获后者将无效,因为AIOOBE 不是 ME。您的ME是AIOOBE的子类型。

另一方面,AIOOBE有一个超类型:IndexOutOfBoundsException。如果你有一个catch子句,你会得到所需的行为,因为AIOOBE IOOBE。

或者你可以自己抛出你的ME:throw new MyException(...)