import java.util.concurrent.CompletableFuture;
public class CompletableFutureExceptionHandling {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
// 模拟第一个异步任务
return "Initial Result";
})
.thenApply(result -> {
// 模拟第二个异步任务,可能抛出异常
if ("Initial Result".equals(result)) {
throw new CustomException("Custom Exception Occurred");
}
return result + " processed";
})
.handle((result, ex) -> {
if (ex != null) {
if (ex instanceof CustomException) {
return "Result for Custom Exception";
} else {
return "Result for other Exceptions";
}
}
return result;
})
.thenApply(finalResult -> {
// 后续任务继续执行
return "Final processing: " + finalResult;
})
.thenAccept(System.out::println);
}
static class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
}