有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

捕获java时的异常处理。lang.ArrayIndexOutOfBoundsException

我是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);
    }
}

结果是: 线程“main”java.lang.ArrayIndexOutOfBoundsException:10在TestClass.doTest(TestClass.java:14)在TestClass.main(TestClass.java:5)中出现异常

为什么不是“MyException在这里”


共 (3) 个答案

  1. # 1 楼答案

    您的方法实际上只抛出ArrayIndexOutOfBoundsException

    您捕获了MyException,但这不是抛出的对象,因此catch子句没有效果

    如果要抛出MyException,则必须修改该方法以捕获ArrayIndexOutOfBoundsException并抛出MyException

  2. # 2 楼答案

    您混淆了子类型-超类型关系

    代码本身抛出一个ArrayIndexOutOfBoundsException而不是一个MyException。抓住后者是行不通的,因为一个AIOOBE不是一个ME。你的我是艾奥比的一个亚型

    另一方面,AIOOBE有一个超类型:IndexOutOfBoundsException。如果您有一个catch子句,那么您将获得所需的行为,因为AIOOBE是一个IOOBE

    或者你也可以自己扔你的我:throw new MyException(...)

  3. # 3 楼答案

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

    throw new MyException("your message");