面试题答案
一键面试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("Specific Exception");
}
return "Task 1 completed";
})
.handle((result, ex) -> {
if (ex != null) {
if (ex instanceof RuntimeException && "Specific Exception".equals(ex.getMessage())) {
System.out.println("Handling specific exception: " + ex.getMessage());
return "Recovered from specific exception";
} else {
System.out.println("Handling other exception: " + ex.getMessage());
return "Recovered from other exception";
}
}
return result;
})
.thenApply(result -> {
System.out.println("Task 2 processing: " + result);
return result + " -> Task 2";
})
.thenAccept(System.out::println);
// 等待所有任务完成
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在上述代码中:
CompletableFuture.supplyAsync
模拟了一个可能抛出异常的异步任务。handle
方法用于处理前一个任务可能抛出的异常。在handle
方法中,根据异常类型进行不同的处理,并返回相应的恢复结果。thenApply
和thenAccept
等方法继续执行后续的任务分支,即使前一个任务出现异常,经过handle
处理后,后续任务也能正常执行。