java:S2142 False Positive: rethrow in union catch

Rule:

S2142 “InterruptedException” should not be ignored

Environment:

SonarQube Version: 10.0.0.68432

Description:

This code should not raise S2142 but it does (InterruptedException is rethrown properly):

public void catchUnionType () {
    try {
      while (true) {
        // do stuff
      }
    } catch (InterruptedException | java.io.IOException e) { // FP: S2142 here
      unknownField.log(Level.WARN, "Interrupted!", e);
      // clean up state...
      throw e;
    }
  }

This patch (against https://github.com/SonarSource/sonar-java/@132163c) makes the tests fail:

diff --git a/java-checks-test-sources/src/main/files/non-compiling/checks/InterruptedExceptionCheck.java b/java-checks-test-sources/src/main/files/non-compiling/checks/InterruptedExceptionCheck.java
index 71d08c714..249546541 100644
--- a/java-checks-test-sources/src/main/files/non-compiling/checks/InterruptedExceptionCheck.java
+++ b/java-checks-test-sources/src/main/files/non-compiling/checks/InterruptedExceptionCheck.java
@@ -46,6 +46,15 @@ public class InterruptedExceptionCheck {
     } catch (InterruptedException | java.io.IOException e) { // Noncompliant [[sc=14;ec=58]] {{Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here.}}
       unknownField.log(Level.WARN, "Interrupted!", e);
     }
+    try {
+      while (true) {
+        // do stuff
+      }
+    } catch (InterruptedException | java.io.IOException e) {
+      unknownField.log(Level.WARN, "Interrupted!", e);
+      // clean up state...
+      throw e;
+    }
   }

   public void run () throws InterruptedException{
1 Like

Hey @janosvitok ,

Thanks a lot for the nice catch in the rule and the reproducer, it is extremely appreciated! :+1:

From my testing, you don’t even need non-compiling code (with non-resolved unknown element) to make the rule raise FPs.

I created the following ticket to handle it: SONARJAVA-4497

Also, don’t hesitate to open new threads if you see other problems in other rules and manage to reproduce them with minimal code snippets!

Cheers,
Michael

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.