Surprising behavior of Java 8 CompletableFuture exceptionally method

后端 未结 2 2009
失恋的感觉
失恋的感觉 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:45

    This behavior is specified in the class documentation of CompletionStage (fourth bullet):

    Method handle additionally allows the stage to compute a replacement result that may enable further processing by other dependent stages. In all other cases, if a stage's computation terminates abruptly with an (unchecked) exception or error, then all dependent stages requiring its completion complete exceptionally as well, with a CompletionException holding the exception as its cause.

    It’s not that surprising if you consider that you may want to know whether the stage you have invoked exceptionally on failed, or one of its direct or indirect prerequisites.

提交回复
热议问题