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

WBOY
WBOY 转载
2023-08-19 13:49:23 828浏览

在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");
      }
   }
}

输出

sample() method of the SuperTest class

如果你捕获异常的类与抛出的异常不相同或者不是异常的超类,你将会得到一个编译时错误。

同样地,在重写方法时,抛出的异常应该与被重写方法抛出的异常相同或者是其超类,否则会发生编译时错误。

示例

演示

import java.io.IOException;
import java.io.EOFException;
class Demo {
   public void sample() throws IOException {
      System.out.println("sample() method of the Demo class");
   }
}
class SuperTest extends Demo {
   public void sample() throws EOFException {
      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 (EOFException ex){
         System.out.println("Exception");
      }
   }
}

输出

Test.java:12: error: sample() in SuperTest cannot override sample() in Demo
public void sample() throws IOException {
            ^
overridden method does not throw IOException
1 error

D:\>javac Test.java
Test.java:20: error: unreported exception IOException; must be caught or declared to be thrown
   obj.sample();
              ^
1 error

以上就是在Java中覆盖时,父子层次结构对于抛出异常重要吗?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除