如何检查Java中抛出的异常类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27280928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check which exception type was thrown in Java?
提问by jean
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?
在第 5 行,如何检查捕获了哪个异常?
I tried if (e.equals(NotAnInt.class)) {..}
but no luck.
我试过了,if (e.equals(NotAnInt.class)) {..}
但没有运气。
NOTE: NotAnInt
and ParseError
are classes in my project that extend Exception
.
注意:NotAnInt
并且ParseError
是我项目中扩展Exception
.
采纳答案by Erik Kaplun
If you can, alwaysuse separate catch
blocks for individual exception types, there's no excuse to do otherwise:
如果可以,请始终catch
为各个异常类型使用单独的块,没有理由不这样做:
} catch (NotAnInt e) {
// <HANDLE NotAnInt>
} catch (ParseError e) {
// <HANDLE 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) {
// <HANDLE NotAnInt>
} else {
// <HANDLE 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:
然而,共同的步骤也可以提取到方法中以避免if
-else
块:
} catch (NotAnInt e) {
inCommon1(e);
// <HANDLE NotAnInt>
inCommon2(e);
} catch (ParseError e) {
inCommon1(e);
// <HANDLE ParseError>
inCommon2(e);
}
private void inCommon1(e) {
// several steps
// common to
// both cases
}
private void inCommon2(e) {
// several steps
// common to
// both cases
}
回答by DavidGSola
Use multiple catch
blocks, one for each exception:
使用多个catch
块,每个异常一个:
try {
int x = doSomething();
}
catch (NotAnInt e) {
// print something
}
catch (ParseError e){
// print something else
}
回答by anoopknr
If Multiple throws
are happening in a single catch()
then to recognize which Exception, you could use instanceof
operator.
如果多个throws
发生在单个catch()
然后识别哪个 Exception,您可以使用instanceof
运算符。
The java instanceof
operator is used to test whether the object is an instanceof the specified type (class or subclass or interface).
javainstanceof
运算符用于测试对象是否是指定类型(类或子类或接口)的实例。
Try this code :-
试试这个代码:-
catch (Exception e) {
if(e instanceof NotAnInt){
// Your Logic.
} else if if(e instanceof ParseError){
//Your Logic.
}
}