CompletableFuture Handle Exception Recovery

Recover a failed async stage with exceptionally, branch success and failure through handle, and observe outcomes with whenComplete without changing the result.

JavaResilience

Code

snippet
import java.util.concurrent.CompletableFuture;

public class ProfileService {

    static String loadProfile(String id) {
        if (id.equals("ghost")) {
            throw new IllegalStateException("profile not found: " + id);
        }
        return "profile-" + id;
    }

    public static void main(String[] args) {
        // whenComplete:只旁观结果/异常,不替换任何值;join 保证回调先执行完
        String observed = CompletableFuture
                .supplyAsync(() -> loadProfile("42"))
                .whenComplete((profile, error) -> {
                    if (error != null) {
                        System.out.println("observed error: " + error.getMessage());
                    } else {
                        System.out.println("observed value: " + profile);
                    }
                })
                .join();
        System.out.println("main continues with: " + observed);

        // 失败恢复 recovery:exceptionally 把异常换成兜底值,链继续向下走
        String fallback = CompletableFuture
                .supplyAsync(() -> loadProfile("ghost"))
                .exceptionally(error -> "profile-guest")
                .join();
        System.out.println("recovered value: " + fallback);

        // handle:成功与异常共用同一出口,二选一变换
        String rendered = CompletableFuture
                .supplyAsync(() -> loadProfile("ghost"))
                .handle((profile, error) -> profile != null
                        ? profile.toUpperCase()
                        : "anonymous (" + error.getMessage() + ")")
                .join();
        System.out.println("handled value: " + rendered);
    }
}

Inside the snippet

CompletableFuture Handle Exception Recovery is built around the class ProfileService and the functions loadProfile and main.

A guard precedes the IllegalStateException: bad state stops the flow there instead of continuing.

Using it

The main signature, verbatim, is static String loadProfile(String id)

The demo output is labeled (observed error:, observed value:, main continues with:), so every line in the printed output names the step that produced it.

There are 1 call inside main — loadProfile — executed top to bottom.

Key statements

throw new IllegalStateException("profile not found: " + id);
return "profile-" + id;
String observed = CompletableFuture
.supplyAsync(() -> loadProfile("42"))
.whenComplete((profile, error) -> {
if (error != null) {
System.out.println("observed error: " + error.getMessage());
} else {
System.out.println("observed value: " + profile);
}
})
.join();

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code refuses to continue: `IllegalStateException` is thrown while the state is still recoverable.
What does CompletableFuture Handle Exception Recovery print when run?
No setup needed: run the file and look for labeled lines like `observed error:`, `observed value:`, `main continues with:` in the output.