I have a method with a checked exception for a parent class, which can throw exceptions of the type parent and subclass
public void method() throws ParentException {
if( false ) throw new ParentException();
else if( true ) throw new ChildException(); // this one is thrown
}
and I have a cascade catch block, which first has the child exception
try {
method();
} catch (ChildException e) {
// I get here?
} catch (ParentException e) {
// or here?
}
Which block will catch the exception thrown? Since the method declares explicitly the ParentException only, would the ChildException be shown as an instance of ParentException?
On the topic of exception handling, a superclass catch will catch all of its subclasses. Yes.
If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
If SuperClass declares an exception, then the SubClass can only declare the same or child exceptions of the exception declared by the SuperClass and any new Runtime Exceptions, just not any new checked exceptions at the same level or higher.
Exceptions are further subdivided into checked (compile-time) and unchecked (run-time) exceptions. All subclasses of RuntimeException are unchecked exceptions, whereas all subclasses of Exception besides RuntimeException are checked exceptions.
The catch
block will always catch the most specific exception available to it, working its way up from the inheritance hierarchy.
I should stress that your catch blocks must be in the inheritance hierarchy order; that is to say, you may not declare a catch
block with ParentException
followed by ChildException
, as that is a compilation error. What you have there (in terms of catch
blocks) is valid.
A more common use case of this is when handling file IO; you can first catch FileNotFoundException
, then IOException
, should the error be less specific than FileNotFoundException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With