. What is the Java equivalent of aggregateexception of. Net?

Yes Net, the aggregateexception class allows you to throw an exception containing multiple exceptions

For example, if you run multiple tasks in parallel, you will throw an aggregateexception, some of which fail with exceptions

Does java have equivalent classes?

For details, I would like to use it in:

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

Solution

I don't know any built-in or library classes because I never wanted to do this (usually you just link exceptions), but it's not difficult to write myself

You may want to select one of the exceptions as the primary, so it can be used to populate stack traces, etc

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

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>