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);
}
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.
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.
Java 7's Throwable.addSuppressed(Throwable) will do something similar, although it was built for a slightly different purpose (try-with-resource)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With