Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the java equivalent of AggregateException from .net?

In .net the AggregateException class allows you to throw an exception containing multiple exceptions.

For example, you would want to throw an AggregateException if you ran multiple tasks in parallel and some of them failed with exceptions.

Does java have an equivalent class?

The specific case I want 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); 
}
like image 809
Craig Gidney Avatar asked Jul 30 '10 20:07

Craig Gidney


People also ask

What is AggregateException?

AggregateException is used to consolidate multiple failures into a single, throwable exception object. It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query.

How to use AggregateException c#?

Tasks Module Example Public Sub Main() Dim task1 = Task. Run(Sub() Throw New CustomException("This exception is expected!")) Try task1. Wait() Catch ae As AggregateException ' Call the Handle method to handle the custom exception, ' otherwise rethrow the exception. ae.


1 Answers

Java 7's Throwable.addSuppressed(Throwable) will do something similar, although it was built for a slightly different purpose (try-with-resource)

like image 170
Ashwin Jayaprakash Avatar answered Sep 24 '22 00:09

Ashwin Jayaprakash