Sub topic 8
Handling Errors: `exceptionally`, `handle`, and `whenComplete`
This chapter assumes Java 8 lambdas, basic threads and ExecutorService, generics, functional interfaces, and checked versus unchecked exceptions.
A CompletableFuture can finish in two ways:
- Normally, with a result.
- Exceptionally, with a failure.
A dependent stage usually stays exceptional when its previous stage fails. Error-handling methods let you recover, inspect, or record that failure.
Three ways to handle a failure
| Method | Receives | Main purpose | Can replace the result? |
|---|---|---|---|
| `exceptionally` | The exception | Return a fallback after failure | Yes |
| `handle` | The result and exception | Handle success and failure together | Yes |
| `whenComplete` | The result and exception | Observe the outcome | No |
Recovering with `exceptionally`
Use exceptionally when you only need a fallback for failure. Its function runs only when an earlier stage completes exceptionally.
import java.util.concurrent.CompletableFuture;
public class ExceptionallyDemo {
public static void main(String[] args) {
CompletableFuture<Integer> parsed = CompletableFuture
.supplyAsync(() -> Integer.parseInt("abc"))
.exceptionally(ex -> {
System.out.println("Could not parse input: " + ex);
return -1;
});
System.out.println(parsed.join());
}
}The parsing operation throws NumberFormatException. The future then completes exceptionally, so exceptionally returns -1. The next join() receives that normal fallback value.
If the original operation succeeds, exceptionally is skipped and the original value continues through the chain.
Handling both outcomes with `handle`
handle always runs. Its callback receives two arguments:
value, which is the successful result ornullafter failure.ex, which is the exception ornullafter success.
CompletableFuture<String> description = CompletableFuture
.supplyAsync(() -> "42")
.handle((value, ex) -> {
if (ex != null) {
return "invalid input";
}
return "number: " + value;
});Because handle returns a value, it converts either outcome into the result type of the next stage. This is useful when success and failure need one common representation.
Do not assume that value == null means failure. A successful operation can legitimately return null. Check ex instead.
Observing with `whenComplete`
Use whenComplete for side effects such as logging, metrics, or cleanup. It receives the same value and ex pair as handle, but it does not replace the outcome.
CompletableFuture<String> request = CompletableFuture
.supplyAsync(() -> "response")
.whenComplete((value, ex) -> {
if (ex == null) {
System.out.println("Request succeeded: " + value);
} else {
System.out.println("Request failed: " + ex);
}
});If the request fails, request still fails after whenComplete runs. If the callback itself throws an exception, that new exception can also make the dependent stage fail. Keep observation callbacks small and reliable.
Understanding wrapped exceptions
join() throws an unchecked CompletionException when the future fails. Its get() method throws checked ExecutionException instead. In both cases, the original failure is usually available as the cause.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class ErrorTypes {
public static void main(String[] args) {
CompletableFuture<Integer> failed = CompletableFuture.supplyAsync(() -> {
throw new IllegalStateException("database unavailable");
});
try {
failed.join();
} catch (CompletionException ex) {
System.out.println("Wrapper: " + ex.getClass().getSimpleName());
System.out.println("Original: " + ex.getCause().getMessage());
}
}
}The wrapper is part of the CompletableFuture API. When logging or classifying a failure, inspect getCause() rather than treating every failure as a CompletionException.
Choosing the method
Use exceptionally for a simple fallback, such as an empty list or cached value. Use handle when the next stage must receive a success-or-error result. Use whenComplete when the result should continue unchanged and you only need an observation.
Exercise
Which method should you choose when you want to log a failure but still let the future remain failed?
Show answer
Use whenComplete, because it observes the outcome without recovering from or replacing the failure.