Consider a Java class hierarchy such as:
abstract class Exp { public void generate(); }
class EffExp extends Exp {...}
clas PureExp extends Exp {...}
class NewExp extends EffExp {...}
etc, etc.
The implementation of generate inside NewExp was changed to throw an IOException.
public void generate() throws IOException {...}
The other implementations of generate don’t do any IO hence don’t need to throw it. The compiler complains and forces me to declare all methods in the class hierarchy to throw the exception. Is this really the only way forward? It seems rather intrusive.
I could of course catch the exception where it happens, inside NewExp, but that doesn’t really make sense. The exception should propagate to the top and stop the program execution.
The more general question here is: if you have a hierarchy of methods that override each other, do they all have to be declared to throw the same set of exceptions?
Just remember One Rule: –
Checked Exception, decreasing the method visibility.So, if you have to (no choice), make your overriding method throw a
Checked Exception(Note that, you can add a unchecked Exception, though, but it wouldn’t make any sense), just add the exception in the throws clause of the method you are overriding.So, in simple words, the signature of your
overriddenmethod should match exactly with the one that overrides it.Now the simple reasoning behind this is –
Polymorphism.In polymorphism, as you know that, you can have a
super typereference point to a sub class object. So, you can have: –Now, while checking for the existence of
method1, compiler is only concerned about the reference type. So, it checks inSupClass, and allows the access accordingly.Now, imagine what happens, when at runtime, when
refis actually pointing toSubClassobject, JVM finds thatmethod1throws a new exception, that was not checked by thecompiler. It will crash. That is why it is not allowed.