简体   繁体   中英

Expecting the same results from these two CompletableFutures

However testCase2 does not handles the exception and throws an error. Am I missing something? Sorry if I did, quite new to this.

@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

Your testCase2 did handled the exception, you can add extra print statement to check it.

The reason testCase2 throws an Exception is that code:

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

will return a new CompletableFuture but you just discard it, the variable cf in cf.get is still not registered with any exception handler. The code should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM