Course contentsShow
← Java
Lesson 2843 of 2,87051. CompletableFutureFree lesson

exceptionally vs handle: When to Use Each

Comparing exceptionally with handle for error handling and choosing the right approach.

exceptionally vs handle: When to Use Each

What you'll learn: How to choose between exceptionally and handle for error handling in CompletableFuture pipelines.

By now you've seen exceptionally as your error recovery tool, but Java provides another method called handle that can also deal with exceptions. Understanding when to reach for each one will make your async code cleaner and more intentional.

The Core Difference

exceptionally is like a dedicated catch block — it only runs when something goes wrong. The function you provide receives only the Throwable, and you return a recovery value.

handle, on the other hand, is like a finally block with access to both success and failure outcomes. It receives both the result (if successful) and the exception (if failed) — one will be null, the other present. You must check which scenario occurred and return an appropriate value.

When to Use exceptionally

Use exceptionally when you want to:

  • Provide a fallback value only on error
  • Keep success path logic separate and clean
  • Log errors and return defaults without examining successful results
future.exceptionally(ex -> {
    System.err.println("Failed: " + ex.getMessage());
    return "default";
});

When to Use handle

Use handle when you need to:

  • Transform both success and failure cases in one place
  • Apply conditional logic that depends on whether an error occurred
  • Convert exceptions into normal results as part of unified processing
future.handle((result, ex) -> {
    if (ex != null) return "Error: " + ex.getMessage();
    return "Success: " + result.toUpperCase();
});

Key Takeaway: Use exceptionally for simple error recovery with fallbacks; use handle when you need unified control over both successful and failed outcomes in a single transformation step.