Will a subclass catch block catch a checked parent

2020-08-17 05:34发布

问题:

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?

回答1:

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.