捕获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在这里”
# 1 楼答案
您的方法实际上只抛出
ArrayIndexOutOfBoundsException
您捕获了
MyException
,但这不是抛出的对象,因此catch
子句没有效果如果要抛出
MyException
,则必须修改该方法以捕获ArrayIndexOutOfBoundsException
并抛出MyException
# 2 楼答案
您混淆了子类型-超类型关系
代码本身抛出一个
ArrayIndexOutOfBoundsException
而不是一个MyException
。抓住后者是行不通的,因为一个AIOOBE不是一个ME。你的我是艾奥比的一个亚型另一方面,AIOOBE有一个超类型:
IndexOutOfBoundsException
。如果您有一个catch子句,那么您将获得所需的行为,因为AIOOBE是一个IOOBE或者你也可以自己扔你的我:
throw new MyException(...)
# 3 楼答案
doTest方法不会引发自定义异常。要抛出异常,请使用