Java8 CompletableFuture(3)异常处理 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>() {
          
   

			@Override
			public 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;

经验分享 程序员 微信小程序 职场和发展