reo*_*eox 5 java exception-handling
有没有更好的方法来捕获带有消息的特定异常然后执行以下操作:
try{
methodThatWillProbablyThrowASocketException();
} catch(SocketException e){
if(e.getMessage().contains("reset")){
// the connection was reset
// will ignore
} else{
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
例如,这HttpStatusException给了我方法getStatusCode(),我可以轻松地比较错误状态是 404 还是 502,并且可以决定要做什么:
try{
methodThatWillProbablyThrowAHTTPException();
} catch(HttpStatusException e){
if(e.getStatusCode() == 404){
// not found, will not continue
}
if else(e.getStatusCode() == 502){
// server errror, try again
} else{
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
大多数其他异常不给我探测器方法,只是消息。
所以我的问题是,这是正确的方法吗?与 String 比较?或者,还有更好的方法?
只做一件事。
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause%28%29
公共 Throwable getCause()
为不同的异常定义你想要的代码比如空指针101,,等等......
到处都使用该类。因此,您只需编写一次异常,就可以在尽可能多的项目中使用。
构建课程后,它将可重复使用以满足您的所有需求
如果你遇到新的情况,只更新这个类,所有的事情都会完成
根据我的说法,这是一个更好的解决方案......
这样您就可以获得您正在寻找的功能。你必须自己做。