面试题答案
一键面试-
异常捕获与处理方式:
- 在CompletableFuture任务链中,可以使用
exceptionally
方法来捕获并处理异常。exceptionally
方法接收一个Function
,该Function
的输入是异常,返回值是在出现异常时要返回的结果。 - 还可以使用
whenComplete
或whenCompleteAsync
方法,它们会在任务完成(包括正常完成和异常完成)时执行,但不会改变任务的返回结果。如果需要在异常时返回特定结果,还是需要结合exceptionally
方法。 - 另外,
handle
和handleAsync
方法也可以处理异常,它们接收一个BiFunction
,第一个参数是正常的结果(如果有),第二个参数是异常(如果有),返回值是处理后的结果。
- 在CompletableFuture任务链中,可以使用
-
代码示例:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExceptionHandling {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("模拟异常");
}
return "任务正常结果";
})
.exceptionally(ex -> {
System.out.println("捕获到异常: " + ex.getMessage());
return "异常时的替代结果";
})
.thenAccept(System.out::println);
// 使用handle方法的示例
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("模拟异常");
}
return "任务正常结果";
})
.handle((result, ex) -> {
if (ex != null) {
System.out.println("handle捕获到异常: " + ex.getMessage());
return "handle异常时的替代结果";
}
return result;
})
.thenAccept(System.out::println);
try {
// 获取最终结果,如果异常未处理,这里会抛出异常
String result = CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("模拟异常");
}
return "任务正常结果";
})
.get();
System.out.println("最终结果: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
上述代码中,通过CompletableFuture.supplyAsync
创建异步任务,然后使用exceptionally
和handle
方法分别展示了捕获和处理异常的方式。thenAccept
用于接收最终的结果并打印。同时也展示了通过get
方法获取结果时,如果异常未在前面处理,这里会抛出异常的情况。