【问题标题】:Exception declaration in inheritance?继承中的异常声明?
【发布时间】: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 表示法。重写的方法允许我将StringIndexOutOfBoundExceptionRunTimeExceptionArrayIndexOutOfBoundException 一起抛出,但不能抛出任何其他异常,例如Exception

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

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

感谢您的帮助。

【问题讨论】:

  • 你总是可以抛出未经检查的异常。尝试检查异常。
  • @chrylis,+1。根据我的测试,它指出被覆盖的方法中的异常必须相同,或者是超类方法中抛出的异常的子类。

标签: java exception-handling


【解决方案1】:

真正简单的答案是,您并没有压倒您的想法。父类声明了一个函数public void checkExcpetions (),而你有一个函数public void checkException ()。这是两个不同的函数,所以没有编译器错误

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

【讨论】:

  • +1 表示注释。我已经更新了我的问题以获取更多查询。
猜你喜欢
  • 1970-01-01
  • 2016-07-20
  • 2019-07-16
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 2012-10-19
相关资源
最近更新 更多