Exception Handling in Structured Concurrency: ExecutionException, Causes and Custom Exceptions
How failures travel out of a StructuredTaskScope in Java 27 and 28: ExecutionException and its cause, mapping causes with pattern matching, letting join() exceptions propagate, choosing an unchecked exception type, fallbacks inside subtasks, stack traces, and interrupts.
kvi5hnuCode Sprout team member8 min readOn this page
When a subtask throws, its exception lives in another thread. Structured concurrency's job is to bring it back to the owner, at join(), as if the subtask had been an ordinary method call. This article shows how that works in Java 27 and 28, and the patterns for handling what comes out.
The path of an exception

- A subtask throws, say
SoldOut, in its own thread. - The joiner sees the failed subtask. The throwing joiners record the first failure and cancel the scope.
join(), running in the owner, asks the joiner for the outcome. The joiner throws a new exception, by defaultExecutionException, with the subtask's exception as its cause.- The owner handles it or lets it propagate to its caller.
Only one exception comes out of join(). Siblings that were cancelled see InterruptedException in their own threads, but that never becomes the scope's outcome.
The patterns
The demo shows four ways of dealing with failures. It uses the Java 27 preview API (java --enable-preview BookingErrors.java on Java 27, no flag on Java 28).
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class BookingErrors {
// Domain exceptions a subtask may throw
static class PaymentDeclined extends RuntimeException {
private static final long serialVersionUID = 1L;
PaymentDeclined(String m) { super(m); }
}
static class SoldOut extends RuntimeException {
private static final long serialVersionUID = 1L;
SoldOut(String m) { super(m); }
}
/** An unchecked exception for callers that don't want to handle ExecutionException. */
static class BookingFailed extends RuntimeException {
private static final long serialVersionUID = 1L;
BookingFailed(Throwable cause) { super("booking failed", cause); }
}
static String charge(String card) throws InterruptedException {
Thread.sleep(100);
if (card.startsWith("0000")) throw new PaymentDeclined("card declined by issuer");
return "payment ok";
}
static String reserveSeat(String flight) throws InterruptedException {
Thread.sleep(150);
if (flight.equals("TP 1940")) throw new SoldOut("no seats left on " + flight);
return "seat 14C";
}
static String recommendations(String city) throws InterruptedException {
Thread.sleep(50);
throw new IllegalStateException("recommendation engine offline");
}
// 1. Catch ExecutionException and map the cause to a message for the customer
static String book(String card, String flight) throws InterruptedException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> payment = scope.fork(() -> charge(card));
Subtask<String> seat = scope.fork(() -> reserveSeat(flight));
scope.join();
return "confirmed: " + payment.get() + ", " + seat.get();
} catch (ExecutionException e) {
return switch (e.getCause()) {
case PaymentDeclined p -> "please try another card (" + p.getMessage() + ")";
case SoldOut s -> "that flight is full, here are alternatives (" + s.getMessage() + ")";
default -> "something went wrong, please retry";
};
}
}
// 2. Let it propagate: the method declares what join() throws
static List<String> seatMaps(List<String> flights) throws InterruptedException, ExecutionException {
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow())) {
for (String f : flights) scope.fork(() -> reserveSeat(f));
return scope.join();
}
}
// 3. An unchecked exception type chosen by the joiner (Java 27+)
static List<String> seatMapsUnchecked(List<String> flights) throws InterruptedException {
try (var scope = StructuredTaskScope.open(
Joiner.<String, BookingFailed>allSuccessfulOrThrow(BookingFailed::new))) {
for (String f : flights) scope.fork(() -> reserveSeat(f));
return scope.join();
}
}
// 4. Optional data: handle the failure inside the subtask, with a fallback
static String tripPage(String city) throws InterruptedException, ExecutionException {
try (var scope = StructuredTaskScope.open()) {
Subtask<String> seat = scope.fork(() -> reserveSeat("TP 1350"));
Subtask<String> tips = scope.fork(() -> {
try {
return recommendations(city);
} catch (IllegalStateException e) {
return "popular places in " + city; // degrade, don't fail the page
}
});
scope.join();
return seat.get() + " | " + tips.get();
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("1. " + book("4111 1111", "TP 1350"));
System.out.println("1. " + book("0000 1111", "TP 1350"));
System.out.println("1. " + book("4111 1111", "TP 1940"));
try {
seatMaps(List.of("TP 1350", "TP 1940"));
} catch (ExecutionException e) {
System.out.println("2. caller handles it: " + e.getCause().getMessage());
// Where do the stack traces point?
String ownerTrace = Arrays.stream(e.getStackTrace()).map(StackTraceElement::getMethodName)
.filter(m -> m.equals("seatMaps") || m.equals("main")).toList().toString();
String subtaskTop = e.getCause().getStackTrace()[0].getMethodName();
System.out.println("2. ExecutionException trace includes " + ownerTrace + "; cause was thrown in " + subtaskTop);
}
try {
seatMapsUnchecked(List.of("TP 1940"));
} catch (BookingFailed e) {
System.out.println("3. " + e.getMessage() + ", cause: " + e.getCause().getMessage());
}
try {
System.out.println("4. " + tripPage("Lisbon"));
} catch (ExecutionException e) {
System.out.println("4. unexpected: " + e.getCause());
}
}
}
Output:
1. confirmed: payment ok, seat 14C
1. please try another card (card declined by issuer)
1. that flight is full, here are alternatives (no seats left on TP 1940)
2. caller handles it: no seats left on TP 1940
2. ExecutionException trace includes [seatMaps, main]; cause was thrown in reserveSeat
3. booking failed, cause: no seats left on TP 1940
4. seat 14C | popular places in Lisbon
1. Catch and map the cause
book catches ExecutionException right where the scope is, and turns the cause into something the customer can act on. A switch with type patterns keeps the mapping readable:
return switch (e.getCause()) {
case PaymentDeclined p -> "please try another card (" + p.getMessage() + ")";
case SoldOut s -> "that flight is full, here are alternatives (" + s.getMessage() + ")";
default -> "something went wrong, please retry";
};
Always look at getCause(). The ExecutionException itself only says "a subtask failed". Its message is just the cause's toString().
Do this when the method has enough context to decide what the failure means: here, the booking service knows that a declined card means "try another card".
2. Let it propagate
seatMaps has no catch. It declares throws InterruptedException, ExecutionException, the same two checked exceptions as Future.get(), and leaves the decision to its caller. That's right when a lower-level method can't know what a failure means for the request. The caller in main handled it.
Since the scope's exception type is part of its type in Java 27 (StructuredTaskScope<T, R, ExecutionException>), the compiler makes sure every caller deals with it.
3. Pick the exception type
Checked ExecutionException in every signature gets noisy in layered code. The Function overloads of the joiners let the scope throw a type you choose. With allSuccessfulOrThrow(BookingFailed::new), join() throws BookingFailed, an unchecked domain exception, with the subtask's exception as its cause, and seatMapsUnchecked declares only InterruptedException.
Good choices are a domain exception for your service, or CompletionException if you want a standard unchecked wrapper. Whatever you choose, keep the cause: the constructor passed in should call super(message, cause).
The default open() scope always throws ExecutionException. For a custom type with that policy, use open(Joiner.awaitAllSuccessfulOrThrow(BookingFailed::new)).
4. Handle it inside the subtask
Not every failure should fail the operation. Recommendations on a trip page are optional. tripPage catches the failure inside the subtask and returns a fallback, so the subtask succeeds and the scope never sees an error. Use this for optional data, with a narrow catch: catching everything, including InterruptedException, would also swallow cancellation.
Pattern 4 is different from allUntil(s -> false) (article 29). There, subtasks still fail, and the owner examines each handle afterwards. Here, the subtask decides its own fallback.
Stack traces
An ExecutionException has two useful stack traces:
- Its own trace is the owner's:
join(), the method that opened the scope (seatMaps), and its callers (main). That shows where the operation was. - The cause's trace is the subtask's:
reserveSeat, the lambda, and the subtask's thread. That shows where it actually failed.
e.printStackTrace() prints both, with the cause after Caused by:. Loggers do the same when given the exception. Don't log only e.getMessage(): you'd lose the subtask's trace.
InterruptedException
join() also throws InterruptedException when the owner is interrupted, for example because the request was cancelled. By then the scope's close() will cancel the subtasks (article 28), so there's nothing else to clean up. Either let it propagate, or, if you must catch it, restore the flag:
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // keep the interrupt visible to callers
throw new BookingFailed(e);
}
Inside subtasks, the rule is the same: an InterruptedException means "you were cancelled", so stop and rethrow rather than continuing.
Other exceptions from the API
Some exceptions are about misusing the scope, not about subtasks failing. They're unchecked, mean there's a bug, and shouldn't be caught as part of normal handling:
| Exception | Cause |
|---|---|
NullPointerException | a null joiner, task or configuration |
WrongThreadException | fork, join or close from a thread that isn't the owner |
IllegalStateException | get() before join(), join() twice, fork() after join(), closing without join() |
StructureViolationException | scopes closed out of order, or forking with different scoped-value bindings (article 41) |
RejectedExecutionException | the configured thread factory refused to create a thread |
What's current
- In Java 27 (JEP 533) and Java 28 (JEP 543, final), the built-in throwing joiners throw
ExecutionExceptionby default, and each has aFunction<Throwable, X>overload for a custom type. - In Java 25 and 26, the
open()-based previews threw the uncheckedStructuredTaskScope.FailedExceptionfromjoin(). (The original Java 21 to 24 API usedShutdownOnFailure.throwIfFailed(), which threwExecutionException.) Migrating from Java 25 or 26 to Java 27 means replacingcatch (FailedException e)withcatch (ExecutionException e)or choosing a custom type (article 37). - A timeout is reported the same way:
ExecutionExceptionwith aCancelledByTimeoutExceptioncause (article 32).
Common questions
Why did Java 27 switch to a checked ExecutionException?
For consistency with Future.get(), which has always thrown ExecutionException, and so that the compiler reminds callers that a fan-out can fail. Code that prefers unchecked exceptions can pick its own type with the Function overloads.
How do I get all the failures, not just the first?
The throwing joiners only report one. Use Joiner.allUntil(s -> false) and read exception() from every FAILED handle, or write a custom joiner that collects them (article 33). You can attach the extra ones to the main exception with addSuppressed.
Should I catch Exception around a scope?
Rarely. Catch ExecutionException (or your custom type) for subtask failures and InterruptedException for cancellation. A broad catch also captures the programming errors in the table above, which should fail loudly.
Is the cause always exactly the exception the subtask threw?
Yes, for the built-in joiners: the same object, with its original stack trace. For a timeout, the cause is a CancelledByTimeoutException instead.
Summary
- A subtask's exception reaches the owner at
join(), wrapped as the cause of anExecutionException(the default) or of a type you choose. - Map the cause where you know what it means, for example with a type-pattern
switch, or let the exception propagate to a layer that does. - The
Functionoverloads (allSuccessfulOrThrow(BookingFailed::new)and the others) replaceExecutionExceptionwith your own, typically unchecked, exception type. - Handle optional failures inside the subtask with a narrow
catchand a fallback. - Log the whole exception: its own trace shows the owner, and its cause's trace shows the subtask.
- Restore the interrupt flag if you catch
InterruptedException, and treat API exceptions such asWrongThreadExceptionas bugs.
Practice questions
A service logs "quote failed: " + e.getMessage() in its catch (ExecutionException e) block. What useful information is missing from the logs?
Answer
The stack traces. The message only contains the cause's toString(). Neither the subtask's trace (where it failed) nor the owner's trace (which operation was running) is logged. Pass the exception itself to the logger, which prints the trace and the cause chain.
A subtask wraps its body in try { ... } catch (Exception e) { return fallback; }. The scope is cancelled because a sibling failed. What happens in this subtask, and why is it a problem?
Answer
Cancellation interrupts the subtask, and a blocking call throws InterruptedException, which the broad catch swallows: the subtask returns the fallback instead of stopping. Here that only wastes a little work, but if the code went on to do more blocking work, it would keep running while close() waits. Catch only the specific exceptions you want to fall back on.
A layered application doesn't want ExecutionException in every method signature. Name two ways to avoid it while keeping the original failure.
Answer
Use a joiner's Function overload to throw an unchecked type, for example Joiner.awaitAllSuccessfulOrThrow(QuoteFailed::new) or allSuccessfulOrThrow(CompletionException::new). Or catch ExecutionException at the scope and rethrow a domain exception with the original cause: throw new QuoteFailed(e.getCause()). Either way the subtask's exception stays in the cause chain.
Previous: Racing Subtasks in Java: anySuccessfulOrThrow and Hedged Requests
Next: Configuring StructuredTaskScope in Java: Names, Thread Factories and Timeouts

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.