如何正确地从执行器中捕获运行时异常?

假设我有以下代码:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(myRunnable);

现在,如果扔一个,我怎么能抓住它?一种方法是向它提供我自己的实现,并为由此产生的 s 设置自定义 s。另一种方法是包装到包含 try-catch -block 的本地(匿名)。也许还有其他类似的解决方法。但。。。不知何故,这感觉很脏,我觉得它不应该这么复杂。有没有一个干净的解决方案?myRunnableRuntimeExcpetionThreadFactorynewSingleThreadExecutor()uncaughtExceptionHandlerThreadmyRunnableRunnable


答案 1

干净的解决方法是使用 代替 。这将返回一个,可用于检索任务的结果或异常:ExecutorService.submit()execute()Future

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();
}

答案 2

在另一个运行中修饰 runnable,该 runnable 捕获运行时异常并处理它们:

public class REHandler implements Runnable {
    Runnable delegate;
    public REHandler (Runnable delegate) {
        this.delegate = delegate;
    }
    public void run () {
        try {
            delegate.run ();
        } catch (RuntimeException e) {
            ... your fancy error handling here ...
        }
    }
}

executor.execute(new REHandler (myRunnable));

推荐