Surprising behavior of Java 8 CompletableFuture exceptionally method

后端 未结 2 2005
失恋的感觉
失恋的感觉 2020-12-09 01:32

I have encountered strange behavior of Java 8 CompletableFuture.exceptionally method. If I execute this code, it works fine and prints java.lang.RuntimeException

2条回答
  •  醉梦人生
    2020-12-09 01:47

    yes, the behavior is expected, but if you want the original exception which was thrown from one of the previous stages, you can simply use this

    CompletableFuture future = new CompletableFuture<>();
    
    future.completeExceptionally(new RuntimeException());
    
    future.thenApply(v-> v).exceptionally(e -> {
            System.out.println(e.getCause()); // returns a throwable back
            return null;
    });
    

提交回复
热议问题