How to check which exception type was thrown in Java?

exception, java

Solution

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 `if`-`else` 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
}

Problem

How can I determine which type of exception was caught, if an operation catches multiple exceptions? This example should make more sense: ``` try { int x = doSomething(); } catch (NotAnInt | ParseError e) { if (/* thrown error is NotAnInt */) { // line 5 // printSomething } else { // print something else } } ``` On line 5, how can I check which exception was caught? I tried `if (e.equals(NotAnInt.class)) {..}` but no luck. NOTE: `NotAnInt` and `ParseError` are classes in my project that extend `Exception`.

Original source

Related problems