Skip to content

Commit 0410788

Browse files
SONARJAVA-6095 S1166 should not report on exceptions using unnamed variable _ (#5436)
1 parent b5279ce commit 0410788

3 files changed

Lines changed: 14 additions & 1 deletion

File tree

java-checks-test-sources/default/src/main/java/checks/CatchUsesExceptionWithContextCheck.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ private void f(Exception x) {
6565
System.out.println("" + e);
6666
}
6767
}
68+
try {
69+
} catch (Exception _) { // Compliant
70+
}
6871
}
6972

7073
private void g() {

java-checks/src/main/java/org/sonar/java/checks/CatchUsesExceptionWithContextCheck.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ public void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree) {
170170

171171
@Override
172172
public void visitCatch(CatchTree tree) {
173-
if (!isExcludedType(tree.parameter().type()) && !excludedCatchTrees.contains(tree)) {
173+
if (!isExcludedType(tree.parameter().type()) && !excludedCatchTrees.contains(tree) && !tree.parameter().simpleName().isUnnamedVariable()) {
174174
Symbol exception = tree.parameter().symbol();
175175
usageStatusStack.addFirst(new UsageStatus(exception.usages()));
176176
super.visitCatch(tree);

sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S1166.html

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,16 @@ <h3>Exceptions</h3>
6868
LOGGER.warn(message); // Compliant - exception message logged with some contextual information
6969
}
7070
</pre>
71+
<p>Additionally, no issue will be raised if the exception parameter uses the unnamed variable <code>_</code>, which is available starting with Java
72+
21. The unnamed variable makes it explicit that the exception is caught but not needed in the handler (see {rule:java:S7467}).</p>
73+
<pre>
74+
try {
75+
/* ... */
76+
} catch (Exception _) {
77+
// Compliant - unnamed exception parameter is intentionally unused
78+
return defaultValue;
79+
}
80+
</pre>
7181
<h2>Resources</h2>
7282
<ul>
7383
<li> OWASP - <a href="https://owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures/">Top 10 2021 Category A9 - Security Logging and

0 commit comments

Comments
 (0)