Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 318
Coderrr Avatar asked Jan 30 '19 07:01

Coderrr


1 Answers

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

like image 178
jumping_monkey Avatar answered Oct 13 '22 09:10

jumping_monkey