CompletableFuture 异常处理
可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。
public <U> CompletableFuture<U> handle(
BiFunction<? super T, Throwable, ? extends U> fn) {
return uniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn) {
return uniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
return uniHandleStage(screenExecutor(executor), fn);
}
示例代码如下:
CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("Computation error!");
}
return "hello!";
}).handle((res, ex) -> {
// res 代表返回的结果
// ex 的类型为 Throwable ,代表抛出的异常
return res != null ? res : "world!";
});
assertEquals("world!", future.get());
还可以通过 exceptionally() 方法来处理异常情况。
CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
throw new RuntimeException("Computation error!");
}
return "hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionException
return "world!";
});
assertEquals("world!", future.get());
如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。
CompletableFuture<String> completableFuture = new CompletableFuture<>();
// ...
completableFuture.completeExceptionally(
new RuntimeException("Calculation failed!"));
// ...
completableFuture.get(); // ExecutionException
相关推荐
CompletableFuture
CompletableFuture
Java8 CompletableFuture(5)异常处理 handle
Java8 CompletableFuture handle一、handle的作用和特点1. handle的特点2. handle和thenApply的区别3. handle和whenComplete的区别二、测试案例 一、handle的作用和特点 1. handle的特点 在写代码时,我们常用try…catch…finally这样的代码块处理异常。 而handle就像finally,不论正常返回还是出异常都会进入handle,类似whenComplete。 handle()一般接收new BiFuncti
CompletableFuture异步编程[源码]
本文详细介绍了Java 8中引入的CompletableFuture类,它是一个强大的异步编程工具,扩展了Future接口并实现了CompletionStage接口。文章首先解释了CompletableFuture的基本概念及其与Future、CompletionStage的关系,然后详细介绍了其常用方法,包括创建实例、完成时触发操作、组合多个CompletableFuture、异常处理等。最后,通过一个制作肉丝面的实际案例,展示了如何使用CompletableFuture实现并发编程,显著提升效率。文章内容全面,适合希望深入了解Java异步编程的开发者阅读。
CompletableFuture详解[可运行源码]
本文详细介绍了Java 8中引入的CompletableFuture类,它实现了Future接口,用于表示异步计算的结果。文章首先解释了CompletableFuture的定义和优势,包括其丰富的异常处理、组合多个计算任务以及链式调用的能力。接着,文章详细说明了如何使用CompletableFuture,包括创建、依赖一个或多个CompletableFuture的方法,以及其原理和设计思想。此外,文章还列举了使用CompletableFuture时的注意事项,如线程池管理、死锁避免、异常处理和超时设置等。最后,文章提到了工具类的使用,为开发者提供了全面的异步编程指南。
CompletableFuture:Java异步编程利器.pptx.pptx
CompletableFuture的定义 CompletableFuture是Java 8中引入的一种新的Future,它是一种异步编程工具,可以用于处理异步任务的结果。 CompletableFuture的特性 CompletableFuture具有非阻塞性,可以在等待结果的同时执行其他任务,而且它支持链式调用,使代码更加简洁易读。 CompletableFuture的使用场景 CompletableFuture常用于需要处理异步任务的场景,如并发请求、数据处理等,它可以提高程序的运行效率和响应速度。


