Java相当于.net的Ag aggregateException是什么?

2022-09-02 10:39:01

在 .net 中,AggregateException 类允许您引发包含多个异常的异常。

例如,如果您并行运行了多个任务,并且其中一些任务失败并出现异常,则可能需要抛出 AggregateException。

Java有等效的类吗?

我想在具体案例中使用它:

public static void runMultipleThenJoin(Runnable... jobs) {
    final List<Exception> errors = new Vector<Exception>();
    try {
        //create exception-handling thread jobs for each job
        List<Thread> threads = new ArrayList<Thread>();
        for (final Runnable job : jobs)
            threads.add(new Thread(new Runnable() {public void run() {
                try {
                    job.run();
                } catch (Exception ex) {
                    errors.add(ex);
                }
            }}));

        //start all
        for (Thread t : threads)
            t.start();

        //join all
        for (Thread t : threads)
            t.join();            
    } catch (InterruptedException ex) {
        //no way to recover from this situation
        throw new RuntimeException(ex);
    }

    if (errors.size() > 0)
        throw new AggregateException(errors); 
}

答案 1

Java 7的Throwable.addSuppressed(Throwable)将做类似的事情,尽管它是为了一个稍微不同的目的而构建的(try-with-resource)。)


答案 2

我不知道任何内置或库类,因为我以前从未想过这样做(通常你只会链接异常),但是自己编写并不难。

您可能希望选择其中一个异常作为“主要”,以便它可用于填充堆栈跟踪等。

public class AggregateException extends Exception {

    private final Exception[] secondaryExceptions;

    public AggregateException(String message, Exception primary, Exception... others) {
        super(message, primary);
        this.secondaryExceptions = others == null ? new Exception[0] : others;
    }

    public Throwable[] getAllExceptions() {

        int start = 0;
        int size = secondaryExceptions.length;
        final Throwable primary = getCause();
        if (primary != null) {
            start = 1;
            size++;
        }

        Throwable[] all = new Exception[size];

        if (primary != null) {
            all[0] = primary;
        }

        Arrays.fill(all, start, all.length, secondaryExceptions);
        return all;
    }

}

推荐