Java8 CompletableFuture handle
一、handle的作用和特点
1. handle的特点
在写代码时,我们常用try…catch…finally这样的代码块处理异常。
而handle就像finally,不论正常返回还是出异常都会进入handle,类似whenComplete。
handle()一般接收new BiFunction<T, Throwable, R>();
- T:就是任务传入的对象类型
- Throwable:就是任务传入的异常
- R:就是handle自己返回的对象类型
2. handle和thenApply的区别
handle和thenApply的区别:
- thenApply:任务出现异常就不会进入thenApply
- handle:任务出现异常也会进入handle,可对异常处理
3. handle和whenComplete的区别
handle和whenComplete的区别:
- handle对传入值进行转换,并产生自己的返回结果,T -> R
- whenComplete的返回值和上级任务传入的结果一致,不能对其转换
二、测试案例
- supplyAsync中线程返回的是部门Dept
- handle接收到传入的Dept,并User赋值deptId和deptName,然后返回User
public class Thread04_Handle {
public static void main(String[] args) throws ExecutionException, InterruptedException {
DeptService deptService = new DeptService();
UserService userService =
1万+


异常处理 handle&spm=1001.2101.3001.11974&articleId=116489984&d=1&t=3&u=79ca74f5a852486e8ba73ffca90c0c69)

被折叠的 条评论
为什么被折叠?



