Search code examples
javaexceptionscjp

Java Certification: How to override methods that define a throws exception?


Can anyone confirm the following in regards to methods that define exceptions thrown when method overriding? I want to be sure I understand it clearly.

Given the following code:

class A
{
    public void doStuff() throws IllegalArgumentException{}
}

class B extends A
{
        public void doStuff() throws NumberFormatException{}
}

class C extends A
{
        public void doStuff() throws Exception{}
}

Only class A and B should compile and not class C. When overriding a method you can narrow the thrown class, but cannot widen it like in class C. The reason behind this I believe is the example in the following code:

class D
{
    doIt(A a)
    {
        try
        {
            a.doStuff();
        }
        catch(IlligalArgumentException e){}
    }
}

Class A could be extended any number of times and so the doStuff() method can also potentially be overriden any number of times, but regardless, the try catch above will always catch the exception.

But if widening were allowed, the above code could potentially miss the exception being thrown and there would be unexpected result in the application.

Is this the correct thinking? Is there anything else I'm missing?

Thanks


Solution

  • If a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass. This is because of Polymorphism. So imo, your thinking is correct.