Java8 CompletableFuture(3)异常处理 exceptionally
Java8 CompletableFuture exceptionally
- 一、前言
- 二、测试案例
一、前言
在写代码时,经常需要对异常进行处理,最常用的就是try catch。
在用CompletableFuture编写多线程时,如果需要处理异常,可以用exceptionally,它的作用相当于catch。
exceptionally的特点:
- 当出现异常时,会触发回调方法exceptionally
- exceptionally中可指定默认返回结果,如果出现异常,则返回默认的返回结果
二、测试案例
public class Thread01_Exceptionally {public static void main(String[] args) throws InterruptedException, ExecutionException {CompletableFuture<Double> future = CompletableFuture.supplyAsync(() -> {if (Math.random() < 0.5) {throw new RuntimeException("抛出异常");}System.out.println("正常结束");return 1.1;}).thenApply(result -> {System.out.println("thenApply接收到的参数 = " + result);return result;}).exceptionally(new Function<Throwable, Double>() {@Overridepublic Double apply(Throwable throwable) {System.out.println("异常:" + throwable.getMessage());return 0.0;}});System.out.println("最终返回的结果 = " + future.get());}
}
当没有出现异常时结果:
正常结束
thenApply接收到的参数 = 1.1
最终返回的结果 = 1.1
当出现异常时结果:
异常:java.lang.RuntimeException: 抛出异常
最终返回的结果 = 0.0
从异常时结果可以看出,exceptionally中捕获了线程的异常信息。
future.get()获取了exceptionally返回的值0.0;
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
