当我们重写抛出Exception的方法时,我们需要遵循一些规则。
当父类方法 未引发任何异常时,子类方法将不会引发任何已检查的异常,但它可能会引发任何未检查的异常。
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