异常覆盖规则

时间:2014-07-18 17:25:17

标签: java override

Java重写规则表示重写的方法不能抛出父异常,但此示例运行正常。任何人都可以对此有所了解吗?

public class TestA {
    public  void display() throws ArithmeticException{
        System.out.println("inside parent");
    }
}


public class Test extends TestA{
    public void display() throws RuntimeException{
     System.out.println("inside child");
   }
}

2 个答案:

答案 0 :(得分:3)

在重写方法中,您始终可以声明它会抛出RuntimeException,因为RuntimeException是未经检查的异常。通常不会声明方法抛出RuntimeException,但如果您愿意,也可以这样做。

Section 8.4.6 of the JLS州:

  

允许但不要求在throws子句中提及未经检查的异常类(第11.1.1节)。

此外,Section 8.4.8.3 of the JLS声明:

  

对于m2的throws子句中列出的每个已检查异常类型,m1的throws子句的擦除(第4.6节)中必须出现相同的异常类或其超类型之一;否则,发生编译时错误。

RuntimeException未经检查,因此不需要在超类方法的throws子句中。

答案 1 :(得分:0)

RuntimeException是未经检查的异常,可以从任何方法抛出。与已检查的方法覆盖的异常规则不同,此处不适用。

相关问题