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:
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).