Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw a Composite Exception in Java

Tags:

java

exception

I'm using ExecutorService, Future and Callable to do parallel processing. Though the Callable's exception can be caught when invoking Future#get, how to catch all the exceptions thrown by all callables and then throw a huge, compound exception, like:

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();
like image 889
Ji ZHANG Avatar asked Jan 30 '26 11:01

Ji ZHANG


2 Answers

If you want to associate multiple exceptions with a single throw, use addSuppressed on your outermost exception.

It won't help you much on the catch side, but comprehensive error handling is never easy, especially after joining multiple threads of control.

like image 75
Barry Kelly Avatar answered Feb 01 '26 02:02

Barry Kelly


Maybe I'm missing something, but

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

Instantiate one of these puppies and load it up with all the exceptions before throwing it.

like image 39
Bohemian Avatar answered Feb 01 '26 02:02

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!