如果操作捕获多个异常,我如何确定捕获了哪种类型的异常?
这个例子应该更有意义:
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
的类。
答案 0 :(得分:29)
如果您不能将这两个案例放在单独的catch
块中,请使用:
if (e instanceof NotAnInt) {
...
}
有时是合理的,比如当你需要2个或更多不同异常类的共享逻辑时。
否则,请使用单独的catch
块:
} catch (NotAnInt e) {
...
} catch (ParseError e) {
...
}
答案 1 :(得分:6)
使用多个catch
块,每个例外一个:
try {
int x = doSomething();
}
catch (NotAnInt e) {
// print something
}
catch (ParseError e){
// print something else
}
答案 2 :(得分:3)
如果单个throws
中发生多个catch()
,则要识别哪个异常,可以使用 instanceof
运算符。
java instanceof
运算符用于测试 对象是否是指定类型(类,子类或接口)的实例 。
尝试此代码:-
catch (Exception e) {
if(e instanceof NotAnInt){
// Your Logic.
} else if if(e instanceof ParseError){
//Your Logic.
}
}
答案 3 :(得分:0)
如果任何人都不知道该方法中引发了什么类型的异常,例如,具有这种可能性的方法很多:
public void onError(Throwable e) {
}
您可以通过以下方式获取异常类
Log.e("Class Name", e.getClass().getSimpleName());
在我的情况下是UnknownHostException
然后使用前面的答案中提到的instanseof
进行一些操作
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
}