How to improve ugly catch block using exception instanceof

623 Views Asked by At

Please pay attention: caller throws parentexception only!!

Say that aexception, and bexception inherit from parentexception.

In method af, it throws aexception, bexception and parentexception.

void af() throws aexception, bexception, parentexception {}

The method caller calls af and throw parentexception only.

void caller() throws parentexception

Here we lost the information of subclasses of parentexception.

The method rootCaller calls the method caller and rootcaller can only catch parentexception thrown by caller and using the following exception process catch block:

void rootCaller() {
    try {
        caller(); 
    } catch(parentexception e) {
    if(e instanceof aexception) {
        ......
    } else   if(e instanceof bexception) {
        ......
    } else   if(e instanceof parentexception) {
        ......
    } else {
    ......
    }
}

This is so ugly and very easy to forget some subclass of parentexception if the subclasses are too many.

Is there anyway to improve such code?

Current answer can not give me any idea:

1, rootCaller cannnot use multi-catch to simplify the process cause caller only throw parentexception.

2, because caller only throw parentexception, there is not any other exception check if the af is changed latter to throws more than aexception and bexception, say cexception.

1

There are 1 best solutions below

2
On

As others have suggested in the comments, you should be using multiple catch clauses.

void rootCaller() {
    try {
        caller();
    } catch (AException e) {
        // ...
    } catch (ParentException e) {
        // ...
    } catch (BException e) {
        // ...
    } catch (AnotherException e) {
        // ...
    } catch (Exception e) {
        // ...
    }
}

The order of the catches matters too. The Exception will be tested against each case in turn and only trigger the first one that matches.

So for example with AException and BException extending ParentException in my above code the catch (BException e) block can never be reached as catch (ParentException e) is reached and executed first.