Exception Handling in supplyAsync
What you'll learn: How exceptions thrown inside supplyAsync are captured and propagated through the CompletableFuture.
The Core Idea
When you execute code asynchronously using supplyAsync, any exception thrown during the computation doesn't crash your program immediately. Instead, CompletableFuture captures that exception and stores it internally. The CompletableFuture completes, but in an "exceptional" state rather than a normal one.
You discover this exception when you try to retrieve the result using get() or join().
How It Works
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("Something went wrong!");
}
return 42;
});
// The exception is stored, not thrown yet
System.out.println(future.isDone()); // true - completed exceptionally
try {
future.get(); // NOW the exception surfaces
} catch (ExecutionException e) {
System.out.println("Caught: " + e.getCause()); // RuntimeException
}
With join(), the behavior is similar but the wrapping differs:
try {
future.join(); // Throws CompletionException (unchecked)
} catch (CompletionException e) {
System.out.println("Caught: " + e.getCause()); // RuntimeException
}
The Key Difference
get()wraps exceptions inExecutionException(checked exception)join()wraps exceptions inCompletionException(unchecked exception)
Both give you access to the original exception via getCause().
Analogy
Think of supplyAsync like mailing a package. If something breaks during shipping, the delivery service doesn't show up at your door and throw the broken pieces at you. Instead, they mark the package as "damaged" and you discover the problem when you open it (get() or join()).
Key Takeaway: Exceptions thrown in supplyAsync are captured by the CompletableFuture and accessed via get() (wrapped in ExecutionException) or join() (wrapped in CompletionException), preventing silent failures while preserving the async programming model.