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

Rethrowing or Wrapping Exceptions

When and how to rethrow exceptions or wrap them in custom exceptions within exceptionally.

Rethrowing or Wrapping Exceptions

You'll learn how to propagate or transform exceptions within the exceptionally handler rather than swallowing them.

The Core Idea

Sometimes you don't want to recover from an exception with a fallback value—you want to handle it differently while still signaling failure. Within an exceptionally block, you can rethrow the original exception (or throw a new one) to propagate errors downstream, allowing later stages to handle them or wrap them in domain-specific exceptions for better clarity.

Why Rethrow or Wrap?

Think of it like a factory quality control line: when you detect a defect, you might want to log it, add context about which station found it, then pass it forward to specialized handlers—not just replace the defective part with a generic substitute.

Rethrowing the Original Exception

CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Database error");
})
.exceptionally(ex -> {
    System.err.println("Caught: " + ex.getMessage());
    throw new RuntimeException(ex); // Rethrow wrapped
})
.thenApply(result -> result.toUpperCase())
.exceptionally(ex -> "RECOVERY"); // Downstream handler

The first exceptionally logs the error but rethrows it, allowing the second exceptionally to provide final recovery logic.

Wrapping in Custom Exceptions

.exceptionally(ex -> {
    if (ex.getCause() instanceof IOException) {
        throw new DataAccessException("Failed to fetch user", ex);
    }
    throw new RuntimeException(ex);
})

Here you inspect the exception type and wrap it in a domain-specific DataAccessException, adding business context.

When to Use This Pattern

  • When you need to log or audit errors but still fail the pipeline
  • When converting low-level exceptions into business-layer exceptions
  • When chaining multiple exceptionally blocks for layered error handling

Key Takeaway: Use throw within exceptionally to rethrow or wrap exceptions, allowing you to add context, log errors, or delegate handling to downstream stages rather than always recovering with a fallback value.