面试题答案
一键面试方式一:使用exceptionally
方法
通过exceptionally
方法可以在任务出现异常时返回一个默认值。
import java.util.concurrent.CompletableFuture;
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);
}
}
方式二:使用whenComplete
方法
whenComplete
方法可以在任务完成(无论是正常完成还是异常完成)时执行指定的操作,可通过判断是否有异常来处理。
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExceptionHandling2 {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
if (Math.random() < 0.5) {
throw new RuntimeException("模拟异常");
}
return "任务正常执行结果";
})
.whenComplete((result, ex) -> {
if (ex != null) {
System.out.println("捕获到异常: " + ex.getMessage());
} else {
System.out.println("任务正常执行,结果: " + result);
}
});
}
}
方式三:使用handle
方法
handle
方法结合了whenComplete
和thenApply
的功能,在任务完成时返回一个新的结果,无论任务是正常完成还是异常完成。
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExceptionHandling3 {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
if (Math.random() < 0.5) {
throw new RuntimeException("模拟异常");
}
return "任务正常执行结果";
})
.handle((result, ex) -> {
if (ex != null) {
System.out.println("捕获到异常: " + ex.getMessage());
return "默认值";
}
return result;
})
.thenAccept(System.out::println);
}
}