- 使用
exceptionally
方法:
exceptionally
方法用于处理CompletableFuture
中的异常。当CompletableFuture
发生异常时,exceptionally
方法中的回调函数会被执行,返回一个默认值或进行异常处理。
- 示例代码:
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExceptionHandling {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("Simulated exception");
}
return "Success result";
})
.exceptionally(ex -> {
System.out.println("Caught exception: " + ex.getMessage());
return "Default value";
})
.thenAccept(System.out::println);
}
}
- 使用
whenComplete
方法:
whenComplete
方法会在CompletableFuture
完成(无论是正常完成还是异常完成)时执行。它接收两个参数,第一个是正常完成时的结果(如果有异常则为null
),第二个是异常(如果正常完成则为null
)。
- 示例代码:
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExceptionHandling2 {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("Simulated exception");
}
return "Success result";
})
.whenComplete((result, ex) -> {
if (ex != null) {
System.out.println("Caught exception: " + ex.getMessage());
} else {
System.out.println("Result: " + result);
}
});
}
}