44

In one of my method , interrupted exception and execution exception is coming. I put in try catch like this.

try{

  //my code
}catch(InterruptedException|ExecutionException e)

  Log.error(" logging it");
  throw new MonitoringException("it failed" , e)


//monitoringexception extends RunTimeException

Also in my method I put throws InterruptedException,ExecutionException

I am getting below critical error in sonar - Either re-interrupt this method or rethrow the "InterruptedException"

Anyone know how to fix this.

Please help immediately.

Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
Coderrr
  • 441
  • 1
  • 4
  • 4

1 Answers1

69

To "re-interrupt" as a best practice:

try{
    //some code
} catch (InterruptedException ie) {
    logger.error("InterruptedException: ", ie);
    Thread.currentThread().interrupt();
} catch (ExecutionException ee) {
    logger.error("ExecutionException: ",ee);
}

Usually, when a thread is interrupted, whoever is interrupting the thread, wants the thread to exit what it's currently doing.

However, make sure that you do NOT multi-catch:

catch (InterruptedException | ExecutionException e) {     
  logger.error("An error has occurred: ", e);
  Thread.currentThread().interrupt();
}

We do not want ExecutionException to be "re-interrupted".

BONUS:
If you are interested, you can play with the examples here


Cheers

jumping_monkey
  • 5,941
  • 2
  • 43
  • 58