面试题答案
一键面试在Java中,CompletableFuture
可以通过以下几种方式捕获并处理异步任务执行过程中抛出的异常:
-
使用
exceptionally
方法:exceptionally
方法用于处理CompletableFuture
执行过程中抛出的异常,并返回一个新的CompletableFuture
,这个新的CompletableFuture
的结果是处理异常后的结果。CompletableFuture.supplyAsync(() -> { if (Math.random() > 0.5) { throw new RuntimeException("模拟异常"); } return "任务正常执行结果"; }).exceptionally(ex -> { System.err.println("捕获到异常: " + ex.getMessage()); return "异常处理后的默认结果"; }).thenAccept(System.out::println);
-
使用
whenComplete
方法:whenComplete
方法会在CompletableFuture
执行完成(无论是正常完成还是异常完成)时执行,它接收两个参数,第一个是正常的结果(如果有异常则为null
),第二个是异常(如果正常完成则为null
)。CompletableFuture.supplyAsync(() -> { if (Math.random() > 0.5) { throw new RuntimeException("模拟异常"); } return "任务正常执行结果"; }).whenComplete((result, ex) -> { if (ex != null) { System.err.println("捕获到异常: " + ex.getMessage()); } else { System.out.println("任务正常执行结果: " + result); } });
-
使用
handle
方法:handle
方法结合了whenComplete
和thenApply
的功能,它在CompletableFuture
执行完成(正常或异常)时执行,并返回一个新的CompletableFuture
,新的CompletableFuture
的结果由handle
方法的返回值决定。CompletableFuture.supplyAsync(() -> { if (Math.random() > 0.5) { throw new RuntimeException("模拟异常"); } return "任务正常执行结果"; }).handle((result, ex) -> { if (ex != null) { System.err.println("捕获到异常: " + ex.getMessage()); return "异常处理后的默认结果"; } else { return result; } }).thenAccept(System.out::println);