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.
解决方案
If you can't put the two cases in separate catch blocks, use:
if (e instanceof NotAnInt) {
...
}
which is sometimes justified, like when you need shared logic for 2 or more different exception classes.
Otherwise, use separate catch blocks:
} catch (NotAnInt e) {
...
} catch (ParseError e) {
...
}