If an InterruptedException
or a ThreadDeath
error is not handled properly, the information that the thread was
interrupted will be lost. Handling this exception means either to re-throw it or manually re-interrupt the current thread by calling
Thread.interrupt()
. Simply logging the exception is not sufficient and counts as ignoring it. Between the moment the exception is caught
and handled, is the right time to perform cleanup operations on the method’s state, if needed.
Failing to interrupt the thread (or to re-throw) risks delaying the thread shutdown and losing the information that the thread was interrupted - probably without finishing its task.
public void run () { try { /*...*/ } catch (InterruptedException e) { // Noncompliant; logging is not enough LOGGER.log(Level.WARN, "Interrupted!", e); } }
public void run () { try { /* ... */ } catch (InterruptedException e) { // Compliant; the interrupted state is restored LOGGER.log(Level.WARN, "Interrupted!", e); /* Clean up whatever needs to be handled before interrupting */ Thread.currentThread().interrupt(); } } public void run () { try { /* ... */ } catch (ThreadDeath e) { // Compliant; the error is being re-thrown LOGGER.log(Level.WARN, "Interrupted!", e); /* Clean up whatever needs to be handled before re-throwing */ throw e; } }