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..5efcbeb257 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,33 @@ private void f(Exception x) { System.out.println("" + e); } } + + // Unnamed exception variables + try { + } catch (Exception _) { // Compliant + } + + try { + } catch (Exception _) { // Compliant + try { + } catch (Exception _) { // Compliant + } + } + + try { + } catch (Exception _) { // Compliant + try { + } catch (Exception z) { // Noncompliant {{Either log or rethrow this exception.}} + } + } + + try { + } catch (Exception e) { // Compliant + 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..9628b974e8 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 @@ -174,7 +174,8 @@ public void visitCatch(CatchTree tree) { Symbol exception = tree.parameter().symbol(); usageStatusStack.addFirst(new UsageStatus(exception.usages())); super.visitCatch(tree); - if (usageStatusStack.pop().isInvalid() && !exception.isUnknown()) { + if (usageStatusStack.pop().isInvalid() && !exception.isUnknown() + && !isExceptionVariableUnnamed(tree.parameter())) { context.reportIssue(this, tree.parameter(), "Either log or rethrow this exception."); } } @@ -207,6 +208,10 @@ public void visitMemberSelectExpression(MemberSelectExpressionTree tree) { } + private boolean isExceptionVariableUnnamed(VariableTree parameter) { + return parameter.simpleName().isUnnamedVariable(); + } + private boolean isExcludedType(Tree tree) { if (tree.is(Kind.UNION_TYPE)) { return ((UnionTypeTree) tree).typeAlternatives().stream().allMatch(this::isExcludedType);