use*_*433 4 java error-handling executionexception
我的代码的一部分是抛出java.util.concurrent.ExecutionException异常.我怎么处理这个?我可以使用throws条款吗?我对java有点新鲜.
cor*_*iKa 12
这取决于你Future如何处理它的关键任务.事实是你不应该得到一个.如果在您Future未执行的代码中执行了某些操作,则只会遇到此异常.
当你catch(ExecutionException e)应该能够e.getCause()用来确定你的身上发生了什么Future.
理想情况下,您的例外不会像这样冒泡到表面,而是直接在您的表面处理Future.
您应该调查并处理 ExecutionException 的原因。
《Java Concurrency in Action》一书中描述的一种可能性是创建launderThrowable负责展开泛型的方法ExecutionExceptions
void launderThrowable ( final Throwable ex )
{
if ( ex instanceof ExecutionException )
{
Throwable cause = ex.getCause( );
if ( cause instanceof RuntimeException )
{
// Do not handle RuntimeExceptions
throw cause;
}
if ( cause instanceof MyException )
{
// Intelligent handling of MyException
}
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
如果您想要处理异常,事情就非常简单了。
public void exceptionFix1() {
try {
//code that throws the exception
} catch (ExecutionException e) {
//what to do when it throws the exception
}
}
public void exceptionFix2() throws ExecutionException {
//code that throws the exception
}
Run Code Online (Sandbox Code Playgroud)
请记住,第二个示例必须包含在try-catch执行层次结构中某个位置的块中。
如果您希望修复该异常,我们将需要查看您的更多代码。
| 归档时间: |
|
| 查看次数: |
44094 次 |
| 最近记录: |