Hi Friends,
Hope all of you are fine.
I've a small doubt in Exceptions(actually in a question from Kathy Sierra's book, Q3 in CH-5 in SCJP1.5).
Following is the program:
import java.io.*;
class Master {
String doFileStuff() throws FileNotFoundException { return "a"; }
}
class Slave extends Master {
public static void main(String[] args)
{
String s = null;
try
{
s = new Slave().doFileStuff();
}
catch ( Exception x)
{
s = "b";
}
System.out.println(s);
}
// following line irks me --> String doFileStuff() throws NumberFormatException { return "b"; }
}
In above program class Slave overrides the doFileStuff() method of its superclass Master.
But is it a legal override?
I've checked it compiles fine
but I've following doubt:
NumberFormatException is not a subclass of FileNotFoundException.
According to KS book, pg 102 says:
"The overriding method must NOT throw checked exceptions that are new
or broader than those declared by the overridden method. For example, a
method that declares a FileNotFoundException cannot be overridden by a
method that declares a SQLException, Exception, or any other non-runtime
exception unless it's a subclass of FileNotFoundException."
What I think is that the
NumberFormatException is a newer checked Exception in this case and this should not be allowed by the compiler?
Please correct me where I am wrong and provide an explanation for this.
Thanks a lot friends,
Nitin