Reputation: 571
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.
Upvotes: 57
Views: 78522
Reputation: 7779
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".
The reason why Sonar suggests to re-interrupt the thread is because by the time the exception occurs, the thread's interrupted state may have been cleared, so if the exception is not handled properly the fact that the thread was interrupted will be lost. Example from InterruptedException's doc:
if (Thread.interrupted()) // Clears interrupted status!
throw new InterruptedException();
BONUS:
If you are interested, you can play with the examples here
Cheers
Upvotes: 94