Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

How to check which exception type was thrown in Java?

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.

question from:https://stackoverflow.com/questions/27280928/how-to-check-which-exception-type-was-thrown-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...