diff --git a/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java b/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java index f35ce10abc..ceaa44893f 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java +++ b/java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java @@ -65,6 +65,9 @@ private void f(Exception x) { System.out.println("" + e); } } + try { + } catch (Exception _) { // Compliant + } } private void g() { diff --git a/java-checks/src/main/java/org/sonar/java/checks/CatchUsesExceptionWithContextCheck.java b/java-checks/src/main/java/org/sonar/java/checks/CatchUsesExceptionWithContextCheck.java index 88c031030a..65e994d0e9 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/CatchUsesExceptionWithContextCheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/CatchUsesExceptionWithContextCheck.java @@ -170,7 +170,7 @@ public void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree) { @Override public void visitCatch(CatchTree tree) { - if (!isExcludedType(tree.parameter().type()) && !excludedCatchTrees.contains(tree)) { + if (!isExcludedType(tree.parameter().type()) && !excludedCatchTrees.contains(tree) && !tree.parameter().simpleName().isUnnamedVariable()) { Symbol exception = tree.parameter().symbol(); usageStatusStack.addFirst(new UsageStatus(exception.usages())); super.visitCatch(tree); diff --git a/sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S1166.html b/sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S1166.html index 817abcb5bd..ce600dff0f 100644 --- a/sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S1166.html +++ b/sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S1166.html @@ -68,6 +68,16 @@

Exceptions

LOGGER.warn(message); // Compliant - exception message logged with some contextual information } +

Additionally, no issue will be raised if the exception parameter uses the unnamed variable _, which is available starting with Java +21. The unnamed variable makes it explicit that the exception is caught but not needed in the handler (see {rule:java:S7467}).

+
+try {
+  /* ... */
+} catch (Exception _) {
+  // Compliant - unnamed exception parameter is intentionally unused
+  return defaultValue;
+}
+

Resources