在Java中覆盖时,父子层次结构对于抛出异常重要吗?

在Java中覆盖时,父子层次结构对于抛出异常重要吗?

当您尝试处理由特定方法抛出的(已检查的)异常时,您需要使用Exception类或发生异常的超类来捕获它。

同样,在重写超类的方法时,如果它抛出异常−

  • 子类中的方法应该抛出相同的异常或其子类型。

  • 子类中的方法不应该抛出其超类型。

  • 您可以在不抛出任何异常的情况下进行重写。

当您有三个名为Demo,SuperTest和Super的类(层次结构)继承时,如果Demo和SuperTest有一个名为sample()的方法。

示例

实时演示

class Demo { public void sample() throws ArrayIndexOutOfBoundsException { System.out.println("sample() method of the Demo class"); } } class SuperTest extends Demo { public void sample() throws IndexOutOfBoundsException { System.out.println("sample() method of the SuperTest class"); } } public class Test extends SuperTest { public static void main(String args[]) { Demo obj = new SuperTest(); try { obj.sample(); }catch (ArrayIndexOutOfBoundsException ex) { System.out.println("Exception"); } } }登录后复制