Details
-
Type:
Bug Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
Message:Either re-interrupt this method or rethrow the "{InterruptedException/ThreadDeath}" that can be caught here.
-
Highlighting:
- Primary: Catch parameter
- Secondary: Method call throwing "InterruptedException"
-
Default Severity:Major
-
Impact:Low
-
Likelihood:High
-
Default Quality Profiles:Sonar way
-
Covered Languages:Java
-
Remediation Function:Constant/Issue
-
Constant Cost:15min
-
Analysis Scope:Main Sources
-
CWE:CWE-391
Description
InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as "ignoring". The throwing of the InterruptedException clears the interrupted state of the Thread, so if the exception is not handled properly the information that the thread was interrupted will be lost. Instead, InterruptedExceptions should either be rethrown - immediately or after cleaning up the method's state - or the thread should be re-interrupted by calling Thread.interrupt() even if this is supposed to be a single-threaded application. Any other course of action risks delaying thread shutdown and loses the information that the thread was interrupted - probably without finishing its task.
Similarly, the ThreadDeath exception should also be propagated. According to its JavaDoc:
If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.
Noncompliant Code Example
public void run () { try { while (true) { // do stuff } }catch (InterruptedException e) { // Noncompliant; logging is not enough LOGGER.log(Level.WARN, "Interrupted!", e); } }
Compliant Solution
public void run () { try { while (true) { // do stuff } }catch (InterruptedException e) { LOGGER.log(Level.WARN, "Interrupted!", e); // Restore interrupted state... Thread.currentThread().interrupt(); } }
See
- MITRE, CWE-391 - Unchecked Error Condition
Attachments
Issue Links
- is implemented by
-
SONARJAVA-1277 Rule : S2142 "InterruptedException" should not be ignored
-
- Closed
-
- is related to
-
SONARJAVA-1695 NPE on S2142: interrupted exception check should not fail when encountering unknownSymbol
-
- Closed
-
-
SONARJAVA-2745 FN on S2142: no issue raised when catching the generic Exception
-
- Closed
-
-
SONARJAVA-3662 Improve rule S2142 to check methods called inside catch block
-
- Closed
-
-
RSPEC-5754 "SystemExit" should be re-raised
- Active
- relates to
-
SONARJAVA-2255 S2142 (don't ignore InterruptedException) add ThreadDeath error
-
- Closed
-