如何检查Java中抛出的异常类型?
如果一个操作捕获多个异常,如何确定捕获了哪种类型的异常 这个例子应该更有意义:如何检查Java中抛出的异常类型?,java,exception-handling,Java,Exception Handling,如果一个操作捕获多个异常,如何确定捕获了哪种类型的异常 这个例子应该更有意义: try { int x = doSomething(); } catch (NotAnInt | ParseError e) { if (/* thrown error is NotAnInt */) { // line 5 // printSomething } else { // print something else } } 在第5行,我如何检查捕获了哪个异常 我尝试了
try {
int x = doSomething();
} catch (NotAnInt | ParseError e) {
if (/* thrown error is NotAnInt */) { // line 5
// printSomething
} else {
// print something else
}
}
在第5行,我如何检查捕获了哪个异常
我尝试了if(e.equals(NotAnInt.class)){..}
,但没有成功
注意:NotAnInt
和ParseError
是我的项目中扩展Exception
的类。如果可以,请始终对单个异常类型使用单独的catch
块,否则没有理由:
} catch (NotAnInt e) {
// handling for NotAnInt
} catch (ParseError e) {
// handling for ParseError
}
…除非您需要共享一些共同的步骤,并且出于简洁的原因希望避免使用其他方法:
} 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
}
但是,也可以将公共步骤提取到方法中,以避免if
-else
块:
} 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
}
使用多个
catch
块,每个异常一个:
try {
int x = doSomething();
}
catch (NotAnInt e) {
// print something
}
catch (ParseError e){
// print something else
}
如果在单个
catch()
中发生多个抛出
,则要识别哪个异常,可以使用instanceof
运算符
javainstanceof
操作符用于测试对象是否是指定类型(类、子类或接口)的实例
请尝试以下代码:-
catch (Exception e) {
if(e instanceof NotAnInt){
// Your Logic.
} else if if(e instanceof ParseError){
//Your Logic.
}
}
如果有人不知道该方法中引发了什么类型的异常,例如一个有很多可能性的方法,比如:
public void onError(Throwable e) {
}
您可以通过以下方式获得异常类:
Log.e("Class Name", e.getClass().getSimpleName());
在我的例子中,它是未知的后异常
然后使用前面答案中提到的instanceof
,采取一些措施
public void onError(Throwable e) {
Log.e("Class Name", e.getClass().getSimpleName());
if (e instanceof UnknownHostException)
Toast.makeText(context , "Couldn't reach the server", Toast.LENGTH_LONG).show();
else
// do another thing
}
制作sever catch:catch(NotAnInt){}catch(ParseError){}可能是的副本,这与你写答案四年前的公认答案有什么不同?@GhostCat谢谢!有如此多的复制粘贴帖子,像这些杂乱无章的问题…这个答案不同于公认的(而且很有帮助),因为它集中在一个解决方案上,这个解决方案隐藏在示例中,在回答文本中没有提及或解释。单独的catch块对我的问题不起作用,因为我正在寻找单一异常类型的根本原因,所以我略读了这些答案。这正是我要寻找的!我有一个多捕获,仅针对一种异常类型,我希望偏离正常行为。在这种情况下,您不能放置多个捕获块吗?“只是好奇。”查恩,我也很好奇。如果
catch
块正在调用某个onException(异常e)
回调,可能会发生这种情况?另一个答案更好,IMHO。对不起,我最近对这篇文章做了一次有害的编辑,现在我已经回复了(并进一步改进了)。