我想知道当我使用 Void 作为返回类型时如何处理 Callable 中的异常。
类似这样的事情:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
call a third party code where an exception is thrown...
return null;
}
});
由于我不需要此可调用的任何结果,因此我不会在调用 executor.submit() 返回的 Future 上调用 get() 。因此异常被吞掉了。
处理此类异常的正确方法是什么?
最佳答案
在你的 call() 方法中 try/catch 怎么样? - 我想这取决于发生异常时你想做什么。
public Void call() throws Exception {
try {
ThirdParty.doSomething();
} catch(SomeTypeException e) {
SomeErrorHandler.handleThisError(e); // E.g. report it to the user
}
return null;
}
关于java - 如何处理来自 Callable<Void> 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054759/