Exception Handling in runAsync
What you'll learn: How exceptions thrown inside runAsync tasks are captured and how to access them from the returned CompletableFuture.
The Core Idea
When you use runAsync to execute a task asynchronously, any exception thrown during that task doesn't crash your program or get logged immediately. Instead, the CompletableFuture returned by runAsync captures and wraps the exception, transitioning to a "completed exceptionally" state. You can then retrieve this exception when you interact with the future.
Think of it like sending a worker on an errand: if something goes wrong, they don't interrupt you immediately. Instead, they complete their task with a note about what went wrong, and you discover the problem when you check in on them.
How Exceptions Are Wrapped
Unlike supplyAsync which returns a value, runAsync returns CompletableFuture<Void>. When an exception occurs:
- The exception is caught internally
- The
CompletableFutureis marked as completed exceptionally - Calling
join()throws aCompletionExceptionwrapping the original exception - Calling
get()throws anExecutionExceptionwrapping the original exception
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
throw new IllegalStateException("Something went wrong!");
});
// Later, when retrieving:
try {
future.join(); // Throws CompletionException
} catch (CompletionException e) {
Throwable cause = e.getCause(); // IllegalStateException
System.out.println("Task failed: " + cause.getMessage());
}
You can check completion status with isCompletedExceptionally() before attempting to retrieve results.
Key Takeaway: Exceptions in runAsync tasks don't propagate immediately—they're wrapped inside the returned CompletableFuture and only surface when you call join() (as CompletionException) or get() (as ExecutionException), allowing graceful error handling.