继承中的异常声明?

时间:2014-05-16 17:39:34

标签: java exception-handling

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表示法。重写方法允许我将StringIndexOutOfBoundExceptionRunTimeExceptionArrayIndexOutOfBoundException一起抛出,而不是像Exception那样抛出任何其他异常。

根据Exception类层次结构,StringIndexOutOfBoundExceptionArrayIndexOutOfBoundException都是IndexOutOfBoundException的子类。

编译器如何以及为什么允许我抛出StringIndexOutOfBoundException,因为ArrayIndexOutOfBoundException永远不会捕获StringIndexOutOfBoundException

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

真正简单的答案是,你不会压倒你的想法。父类声明一个函数public void checkExcpetions (),你有一个函数public void checkException ()。这是两个不同的函数,这就是为什么没有编译器错误

使用@Override标记是让编译器检查您是否覆盖您认为自己的一种方法。在这种情况下,如果您使用标记,则会出现错误,因为您没有覆盖父方法