CompletableFuture 异常捕获方式

1、whenComplete ()

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Oops!");
});

CompletableFuture<String> result = future.thenApply(i -> "Success: " + i)
        .whenComplete((res, ex) -> {
            if (ex != null) {
                System.out.println("Error occurred: " + ex);
            }
        });

result.join(); // 此处会输出错误信息

2、exceptionly ()

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Oops!");
});

CompletableFuture<String> result = future.thenApply(i -> "Success: " + i)
        .exceptionally(ex -> {
            System.out.println("Error occurred: " + ex);
            throw new RuntimeException("Error occurred: " + ex);
        });

result.join(); // 此处会抛出重新抛出的异常

3、Handle ()

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Oops!");
});

CompletableFuture<String> result = future.handle((res, ex) -> {
    if (ex != null) {
        System.out.println("Error occurred: " + ex);
        return "Default Value";
    } else {
        return "Success: " + res;
    }
});

result.join(); // 此处会返回默认值

join()和get()的异同:

  • join()和get()方法都是用来获取CompletableFuture异步之后的返回值
  • join()方法抛出的是uncheck异常(即RuntimeException),不会强制开发者抛出,会将异常包装成CompletionException异常 /CancellationException异常,但是本质原因还是代码内存在的真正的异常,
  • get()方法抛出的是经过检查的异常,ExecutionException, InterruptedException 需要用户手动处理(抛出或者 try catch)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值