在 Java 中,重写抛出异常的方法时需要遵循哪些规则?

javaobject oriented programmingprogramming更新于 2024/7/26 4:51:00

在重写抛出异常的方法时,我们需要遵循一些规则

  • 父类方法不抛出任何异常时,子类方法不能抛出任何已检查异常,但可以抛出任何未检查异常
class Parent {
   void doSomething() {
      // ...
   }
}
class Child extends Parent {
   void doSomething() throws IllegalArgumentException {
      // ...
   }
}
  • 父类方法抛出一个或多个已检查异常时,子类方法可以抛出任何未检查异常
class Parent {
   void doSomething() throws IOException, ParseException {
      // ...
   }
   void doSomethingElse() throws IOException {
      // ...
   }
}
class Child extends Parent {
   void doSomething() throws IOException {
      // ...
   }
   void doSomethingElse() throws FileNotFoundException, EOFException {
      // ...
   }
}
  • 父类方法具有带有未检查的异常的 throws 子句时,子类方法可以抛出零个或任意数量的未检查的异常,即使它们之间没有关联。
class Parent {
   void doSomething() throws IllegalArgumentException {
      // ...
   }
}
class Child extends Parent {
   void doSomething() throws ArithmeticException, BufferOverflowException {
      // ...
   }
}

示例

import java.io.*;
class SuperClassTest{
   public void test() throws IOException {
      System.out.println("SuperClassTest.test() method");
   }
}
class SubClassTest extends SuperClassTest {
   public void test() {
      System.out.println("SubClassTest.test() method");
   }
}
public class OverridingExceptionTest {
   public static void main(String[] args) {
      SuperClassTest sct = new SubClassTest();
      try {
         sct.test();
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

输出

SubClassTest.test() method

相关文章