面试题答案
一键面试在Java流的异步操作模式中,捕获和处理异常通常有以下几种方式:
- 使用
handle
方法:handle
方法可以同时处理正常结果和异常情况。
import java.util.concurrent.CompletableFuture;
public class Main {
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);
}
}
- 使用
exceptionally
方法:exceptionally
方法专门用于处理异常情况,并返回一个替代结果。
import java.util.concurrent.CompletableFuture;
public class Main {
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 Main {
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);
}
});
}
}