Skip to content
Advertisement

Exception propagation in CompletableFuture (java)

How can I propagate exception encountered in the following code inside CompletableFuture.runAsync to my main thread? I want to catch the IllegalStateException in my main thread.

JavaScript

Advertisement

Answer

One option would be to create a Collection of Throwable objects and when the CompletableFuture completes you can add the exception to the Collection (if it’s not null). Then on your main thread you could poll that Collection.

JavaScript

Another option is to use whenComplete with ExecutorService. This may not work if you’re not using an ExecutorService. The idea is that whenComplete will return on the mainThread ExecutorService.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement