Posts

Showing posts from May, 2017

Enjoy quickies with supplyAsync by knowing how to handle exceptions.

PROBLEM: I have a method:  public String getChuckNorrisFact(); This method may also throw an exception, in my case IOException because this method does a service call to get a fact about Chuck Norris from web. I learned about  CompletableFuture  and now I am ASYNCING the shit out everywhere. Here is what I did: CompletableFuture<String> factFuture  = CompletableFuture.supplyAsync(() -> getChuckNorrisFact()); But the compiler tells me to handle or throw the exception, so I do this: CompletableFuture<String> factFuture2 = CompletableFuture.supplyAsync(() -> { try  { return getChuckNorrisFact(); } catch (IOException e ) { e .printStackTrace(); } }); Sadly there is still a compilation error in this. The supplier(lambda expression) in supplyAsync()  needs to return a string but there is no return statement if an exception occurs. So I do this: CompletableFuture<String> factFuture  = Compl