但是testCase2不处理异常并抛出错误。我错过了什么吗?对不起,如果我做了,对此很新。
@Test
public void testCase1() throws Exception {
CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException();
return "Promise";
}).exceptionally((ex) -> {
return "Fake Promise";
}).get();
}
@Test
public void testCase2() throws Exception {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException();
return "Promise";
});
cf.exceptionally((ex) -> {
return "Fake Promise";
});
cf.get();
}
答案 0 :(得分:2)
然而,testCase2不处理异常
您的testCase2
确实处理了异常,您可以添加额外的print
语句进行检查。
testCase2
抛出异常的原因是代码:
cf.exceptionally((ex) -> {
System.out.println("Fake Promise: " + System.nanoTime());
return "Fake Promise";
})
将返回一个新的CompletableFuture
,但您只是将其丢弃,cf
中的变量cf.get
仍未在任何异常处理程序中注册。代码应该是:
@Test
public void testCase2() throws Exception {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException();
return "Promise";
});
CompletableFuture<String> handledCf = cf.exceptionally((ex) -> {
return "Fake Promise";
});
return handledCf.get();
}