3

我正在使用ExecutorService,FutureCallable进行并行处理。虽然Callable调用时可以捕获 ' 异常Future#get,但是如何捕获所有可调用对象抛出的所有异常,然后抛出一个巨大的复合异常,例如:

ExecutorService service = Executors.newFixedThreadPool(5);
List<Future<Void>> futures = new ArrayList<Future<Void>>();
futures.add(service.submit(new TaskA());
futures.add(service.submit(new TaskB());

for (Future<Void> future : futures) {
    try {
        future.get();
    } catch (Exception e) {
        // ???
    }
}

// throw the big exception here

service.shutdown();
4

2 回答 2

3

也许我错过了一些东西,但是

public class CompositeException extends Exception {
    private List<Exception> exceptions = new ArrayList<Exception>();
    public List<Exception> getExceptions() {
        return exceptions;
    }
}

实例化其中一只小狗,并在抛出它之前加载所有异常。

于 2013-11-12T02:35:04.807 回答
3

如果要将多个异常与单个 throw 相关联,addSuppressed请在最外层的异常上使用。

它在捕获方面对您没有多大帮助,但全面的错误处理绝非易事,尤其是在加入多个控制线程之后。

于 2018-07-10T12:55:09.113 回答