Bifrost
Bifrost

Reputation: 427

exception overriding rules

Java overriding rules say that an overridden method can not throw a parent exception but this example is running fine. Can anybody shed some light on this?

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

Upvotes: 0

Views: 181

Answers (2)

Aniket Thakur
Aniket Thakur

Reputation: 68955

RuntimeException are unchecked Exceptions and can be thrown from any method. Unlike checked Exception rules of method overriding do not apply here.

Upvotes: 0

rgettman
rgettman

Reputation: 178263

In an overriding method, you are always allowed to declare that it throws a RuntimeException, because RuntimeExceptions are unchecked exceptions. Usually methods aren't declared to throw RuntimeExceptions, but you can do so if you wish.

Section 8.4.6 of the JLS states:

It is permitted but not required to mention unchecked exception classes (§11.1.1) in a throws clause.

Additionally, Section 8.4.8.3 of the JLS states:

For every checked exception type listed in the throws clause of m2, that same exception class or one of its supertypes must occur in the erasure (§4.6) of the throws clause of m1; otherwise, a compile-time error occurs.

But RuntimeException is unchecked, so it's not required to be in the superclass method's throws clause.

Upvotes: 3

Related Questions