Either re-interrupt this method or rethrow the "InterruptedException issue in sonar

Kunal Raunak picture Kunal Raunak · Jan 30, 2019 · Viewed 13.6k times · Source

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.

Answer

jumping_monkey picture jumping_monkey · Jan 10, 2020

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