jea*_*ean 21 java exception-handling
如果操作捕获多个异常,如何确定捕获的异常类型?
这个例子应该更有意义:
try {
int x = doSomething();
} catch (NotAnInt | ParseError e) {
if (/* thrown error is NotAnInt */) { // line 5
// printSomething
} else {
// print something else
}
}
Run Code Online (Sandbox Code Playgroud)
在第5行,我如何检查捕获的异常?
我试过if (e.equals(NotAnInt.class)) {..}
但没有运气.
注意:NotAnInt
并且ParseError
我的项目中的类是扩展的Exception
.
Eri*_*lun 38
如果您不能将这两个案例放在单独的catch
块中,请使用:
} catch (NotAnInt e) {
// handle NotAnInt
} catch (ParseError e) {
// handle ParseError
}
Run Code Online (Sandbox Code Playgroud)
这有时是合理的,就像你需要两个或更多不同异常类的共享逻辑一样.
否则,使用单独的if
块:
} 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
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*ola 11
使用多个catch
块,每个例外一个:
try {
int x = doSomething();
}
catch (NotAnInt e) {
// print something
}
catch (ParseError e){
// print something else
}
Run Code Online (Sandbox Code Playgroud)
如果throws
单个发生多个,则可以使用运算符catch()
识别哪个Exceptioninstanceof
。
java instanceof
运算符用于测试对象是否是指定类型(类,子类或接口)的实例。
试试这个代码:-
catch (Exception e) {
if(e instanceof NotAnInt){
// Your Logic.
} else if if(e instanceof ParseError){
//Your Logic.
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人不知道该方法中抛出了什么类型的异常,例如具有多种可能性的方法,如下所示:
public void onError(Throwable e) {
}
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式获取异常类
Log.e("Class Name", e.getClass().getSimpleName());
Run Code Online (Sandbox Code Playgroud)
就我而言是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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32196 次 |
最近记录: |