Invoking overriding method that throws Checked exception

Pauwelyn :

After reading Why can't overriding methods throw exceptions, I understand that if method declared as throws a Checked exception, the overriding method in a subclass can only declare to throw that exception or its subclass:

class A {
   public void foo() throws IOException {..}
}

class B extends A {
   @Override
   public void foo() throws SocketException {..} // allowed

   @Override
   public void foo() throws SQLException {..} // NOT allowed
}

So because SocketException IS-A IOException I can declare the overriding method as throws any of subclass of IOException.

In my program, I want to invoke the overriding method declared as throws FileNotFoundException IS-A IOException. also handled with a try-catch block

import java.io.*;
class Sub extends Super{
    public static void main (String [] args){
        Super p = new Sub();
        try {
            p.doStuff();
        }catch(FileNotFoundException e){

        }
    }
    public void doStuff() throws FileNotFoundException{}
}

class Super{
    public void doStuff() throws IOException{}
}

But I am getting that compile-time error: Screenshot

Sub.java:6: error: unreported exception IOException; must be caught or declared to be thrown
                    p.doStuff();
                             ^

What is the reason for that? I'm a little confused because everything that the Base class has also available to the subclasses.

Also much more confusing is the ability to catch Exception and Throwable In addition to IOException (The opposite from Overriding concept).

CKing :

What is the reason for that? I'm a little confused because everything that the Base class has also available to the subclasses.

You need to catch an IOException and not a FilenotFoundException. This is because of the fact that while the doStuff method from the subclass will be called at runtime, the compiler doesn't know about this yet. It only knows about the doStuff method in the super class which declares that it throws an IOException.

To address your edit : The catch block can chose to catch the exact exception that is expected in the try block or it can chose to catch a superclass of the exception. The reasoning behind this has got nothing remotely to do with method overriding.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=451116&siteId=1