【发布时间】:2023-04-09 10:43:01
【问题描述】:
package com.rnd.core.java;
import java.io.IOException;
public class TestExceptionInheritance {
public void checkExcpetions () throws ArrayIndexOutOfBoundsException{
System.out.println("Inside TestExceptionInheritance ParentClass");
throw new ArrayIndexOutOfBoundsException();
}
}
package com.rnd.core.java;
import javax.sound.midi.MidiUnavailableException;
public class TestExceptionInheritance2 extends TestExceptionInheritance {
public void checkException () throws MidiUnavailableException {
System.out.println("Hello");
throw new MidiUnavailableException();
}
@Override
public void checkExcpetions() throws StringIndexOutOfBoundsException {
// TODO Auto-generated method stub
//super.checkExcpetions();
System.out.println("HI");
}
public static void main(String[] args) throws Exception {
TestExceptionInheritance obj = new TestExceptionInheritance2();
obj.checkExcpetions();
}
}
我已经在我的子类中覆盖了父类的 checkException 方法,但是我在这里抛出了一个不同的异常。
我想了解为什么编译器允许我抛出一个完全不同的异常;虽然我知道方法版本会根据引用类型来决定。
-------------------编辑1-------------------------- -
我在被覆盖的方法上添加了一个@override 表示法。重写的方法允许我将StringIndexOutOfBoundException 和RunTimeException 与ArrayIndexOutOfBoundException 一起抛出,但不能抛出任何其他异常,例如Exception。
根据 Exception 类层次结构,StringIndexOutOfBoundException 和 ArrayIndexOutOfBoundException 都是 IndexOutOfBoundException 的子类。
编译器如何以及为什么允许我抛出StringIndexOutOfBoundException,因为ArrayIndexOutOfBoundException 永远不会被StringIndexOutOfBoundException 捕获。
感谢您的帮助。
【问题讨论】:
-
你总是可以抛出未经检查的异常。尝试检查异常。
-
@chrylis,+1。根据我的测试,它指出被覆盖的方法中的异常必须相同,或者是超类方法中抛出的异常的子类。