Returning Default Values on Error
You'll learn how to gracefully provide fallback values when async operations fail, ensuring your program continues smoothly instead of crashing.
The Core Idea
When a CompletableFuture encounters an exception, you often don't want the entire pipeline to fail catastrophically. Instead, you want to return a sensible default value and keep going. The exceptionally method makes this pattern straightforward—it catches exceptions and lets you substitute a safe fallback value in place of the error.
Think of it like ordering food delivery: if your first-choice restaurant is closed (error), you automatically order from your backup restaurant (default value) instead of going hungry.
Common Pattern
The most frequent use of exceptionally is to return a default value when something goes wrong:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Service unavailable");
})
.exceptionally(ex -> 0); // Return 0 on any error
Integer result = future.join(); // result will be 0
Here, even though the async task throws an exception, the pipeline doesn't crash. Instead, exceptionally catches the error and returns 0 as a default.
Real-World Example
CompletableFuture<String> userProfile = CompletableFuture
.supplyAsync(() -> fetchUserFromDatabase())
.thenApply(user -> user.getName())
.exceptionally(ex -> "Guest"); // Default to "Guest" if anything fails
userProfile.thenAccept(name -> System.out.println("Welcome, " + name));
Whether the database call fails, the user doesn't exist, or any other error occurs, your application displays "Welcome, Guest" instead of crashing.
Key Takeaway: Use exceptionally to return default values when errors occur, creating resilient async pipelines that degrade gracefully instead of failing completely.