如何正确地从Executors捕获RuntimeException? [英] How to properly catch RuntimeExceptions from Executors?
问题描述
说我有以下代码:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(myRunnable);
现在,如果 myRunnable
c $ c> RuntimeExcpetion ,我该如何抓住它?一种方法是提供我自己的 ThreadFactory
实现到 newSingleThreadExecutor()
并设置自定义 uncaughtExceptionHandler
用于从它出来的线程
。另一种方法是将 myRunnable
包含到包含try-catch块的本地(匿名) Runnable
。也许还有其他类似的解决方法。但是...不知怎的这种感觉很脏,我觉得它不应该是这么复杂。是否有一个干净的解决方案?
Now, if myRunnable
throws a RuntimeExcpetion
, how can I catch it? One way would be to supply my own ThreadFactory
implementation to newSingleThreadExecutor()
and set custom uncaughtExceptionHandler
s for the Thread
s that come out of it. Another way would be to wrap myRunnable
to a local (anonymous) Runnable
that contains a try-catch -block. Maybe there are other similar workarounds too. But... somehow this feels dirty, I feel that it shouldn't be this complicated. Is there a clean solution?
推荐答案
干净的解决方法是使用 ExecutorService.submit code>而不是
execute()
。这将返回您未来
,您可以使用它来检索任务的结果或异常:
The clean workaround is to use ExecutorService.submit()
instead of execute()
. This returns you a Future
which you can use to retrieve the result or exception of the task:
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable task = new Runnable() {
public void run() {
throw new RuntimeException("foo");
}
};
Future<?> future = executor.submit(task);
try {
future.get();
} catch (ExecutionException e) {
Exception rootException = e.getCause();
}
这篇关于如何正确地从Executors捕获RuntimeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!