继承中的异常声明


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符号。重写的方法允许我抛出StringIndexOutOfBoundExceptionRunTimeException以及ArrayIndexOutOfBoundException,但不抛出任何其他异常,例如Exception

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

为什么编译器允许我抛出StringIndexOutOfBoundException,因为ArrayIndexOutOfBoundException永远不会在StringIndexOutOfBoundException中被捕获。

谢谢你的帮助。

真正简单的答案是你没有覆盖你认为你是什么。父类声明了一个函数public void checkExcpetions (),你有一个函数public void checkException ()。这是两个不同的函数,这就是为什么没有编译错误

使用@Override标签是让编译器检查你是否覆盖了你认为的内容的一种方法。在这种情况下,如果您使用标签,将会出现错误,因为您没有重写父方法

最新更新