Java - 如何检查抛出哪种异常类型? [英] Java - How to check which exception type was thrown?
本文介绍了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
}
}
第5行,我可以检查哪个异常被捕获?
On line 5, how can I check which exception was caught?
我试过 if(e.equals(NotAnInt.class)){..}
但没有运气。
注意: NotAnInt
和 ParseError
是我的项目中的类,扩展异常
。
NOTE: NotAnInt
and ParseError
are classes in my project that extend Exception
.
推荐答案
如果您不能将这两种情况分别放在 catch
块中,请使用:
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.
否则,使用单独的 catch
块:
} catch (NotAnInt e) {
...
} catch (ParseError e) {
...
}
这篇关于Java - 如何检查抛出哪种异常类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文