Skip to content

Commit

Permalink
Style guide allows empty catch blocks with clear parameter names sett…
Browse files Browse the repository at this point in the history
…ing up expectation.

Exempting expected, ignored and ok parameter names.

https://google.github.io/styleguide/javaguide.html#s6.2-caught-exceptions

Inverse flume results (matches that won't be flagged now) : unknown commit

Fixes #1654

PiperOrigin-RevId: 322052035
  • Loading branch information
sumitbhagwani authored and Error Prone Team committed Jul 19, 2020
1 parent 3dad92a commit 1ae734c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Expand Up @@ -20,13 +20,15 @@
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;

import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CatchTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.VariableTree;

/** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */
@BugPattern(
Expand All @@ -39,6 +41,9 @@
)
public class EmptyCatch extends BugChecker implements CatchTreeMatcher {

private static final ImmutableSet<String> EXEMPTED_PARAMETER_NAMES =
ImmutableSet.of("expected", "ok", "ignored");

@Override
public Description matchCatch(CatchTree tree, VisitorState state) {
BlockTree block = tree.getBlock();
Expand All @@ -51,6 +56,11 @@ public Description matchCatch(CatchTree tree, VisitorState state) {
if (ASTHelpers.isJUnitTestCode(state)) {
return NO_MATCH;
}
VariableTree param = tree.getParameter();
if (EXEMPTED_PARAMETER_NAMES.stream()
.anyMatch(paramName -> param.getName().contentEquals(paramName))) {
return NO_MATCH;
}
return describeMatch(tree);
}
}
Expand Up @@ -126,11 +126,32 @@ public void catchIsLoggedOnly() {
}

@Test
public void expectedException() {
public void expectedExceptionInTest() {
try {
System.err.println();
fail();
} catch (Exception expected) {
}
}

public void expectedException() {
try {
System.err.println();
} catch (Exception expected) {
}
}

public void ignoredException() {
try {
System.err.println();
} catch (Exception ignored) {
}
}

public void okException() {
try {
System.err.println();
} catch (Exception ok) {
}
}
}

0 comments on commit 1ae734c

Please sign in to comment.