Search code examples
javamultithreadingasynchronouscompletable-futureruntimeexception

How To throw RuntimeExcpetions from CompletableFuture.whenComplete exception block?


I need to re-throw the runtime exception from the CompletableFuture Exception block to the parent method, but looks like the runtimeException is getting logged at the exception block itself and not propagating back to the parent method. Can anyone please advise/suggest me what I am doing wrong here or is this the right way to throw? I have a function call like below :

void method1(String msg)
{
   try
   {
    method2(msg);
    }
    catch(RuntimeException e)
    {
       throw new CustomException("");
     }
}
void method2(String msg)
{
  CompletableFuture<Void> future = asyncTask.process(msg);
  future.whenComplete((res,ex) ->
        if(ex != null)
        {
           log.error("");
           throw RuntimeException("abc");
         }
        else
         { postProcessTasks(msg);
         }
       );
}

Solution

  • The calling code doesn't wait for the Future to complete or get the status. Here's the core of what needs to be added.

    CompletableFuture<Void> future = asyncTask.process(msg)
      .thenAccept(this::postProcessTasks);
    try {
      future.get();
    } catch (ExecutionException e) {
      Throwable asyncException = e.getCause();
      // .. do something here
    }
    

    If you intend to propagate an asynchronous Exception back to the caller then whenComplete is probably not the call to use; It is meant to handle exceptions within the asynch call.