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
。
感谢您的帮助。
答案 0 :(得分:3)
真正简单的答案是,你不会压倒你的想法。父类声明一个函数public void checkExcpetions ()
,你有一个函数public void checkException ()
。这是两个不同的函数,这就是为什么没有编译器错误
使用@Override
标记是让编译器检查您是否覆盖您认为自己的一种方法。在这种情况下,如果您使用标记,则会出现错误,因为您没有覆盖父方法