How to check which exception type was thrown in Java?

If you can, always use separate catch blocks for individual exception types, there’s no excuse to do otherwise:

} catch (NotAnInt e) {
    // handling for NotAnInt
} catch (ParseError e) {
    // handling for ParseError
}

…unless you need to share some steps in common and want to avoid additional methods for reasons of conciseness:

} catch (NotAnInt | ParseError e) {
    // a step or two in common to both cases
    if (e instanceof NotAnInt) {
        // handling for NotAnInt
    } else  {
        // handling for ParseError
    }
    // potentially another step or two in common to both cases
}

however the steps in common could also be extracted to methods to avoid that ifelse block:

} catch (NotAnInt e) {
    inCommon1(e);
    // handling for NotAnInt
    inCommon2(e);
} catch (ParseError e) {
    inCommon1(e);
    // handling for ParseError
    inCommon2(e);
}

private void inCommon1(e) {
    // several steps
    // common to
    // both cases
}
private void inCommon2(e) {
    // several steps
    // common to
    // both cases
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)