Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a subclass catch block catch a checked parent exception?

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?

like image 462
Sajhu Avatar asked Jul 18 '16 16:07

Sajhu


People also ask

Does declaring a catch of a superclass exception catch all of the subclass exceptions?

On the topic of exception handling, a superclass catch will catch all of its subclasses. Yes.

Can subclass overriding method declare an exception if parent class method doesn't throw an exception?

If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

Can child class exception catch the superclass 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.

Are all subclasses of exception checked?

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.


1 Answers

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.

like image 71
Makoto Avatar answered Oct 01 '22 17:10

Makoto