期望这两个 CompletableFutures 的结果相同

Expecting the same results from these two CompletableFutures

但是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();
}

However testCase2 does not handles the exception

您的 testCase2 确实处理了异常,您可以添加额外的 print 语句来检查它。

testCase2 抛出异常的原因是代码:

cf.exceptionally((ex) -> {
        System.out.println("Fake Promise: " + System.nanoTime());
        return "Fake Promise";
    })

将 return 一个新的 CompletableFuture 但你只是丢弃它, cf.get 中的变量 cf 仍然没有注册任何异常处理程序。代码应该是:

@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();
}