From 716191f65c90c1bded41f0e6b6b7dbef7f9946e6 Mon Sep 17 00:00:00 2001 From: ghm Date: Mon, 1 Jun 2020 01:46:55 -0700 Subject: [PATCH] Flag catching unchecked exceptions as `Exception` This is a bit misleading: it makes an unchecked failure look checked. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=314095901 --- .../bugpatterns/CatchingUnchecked.java | 84 +++++++++++++++++++ .../scanner/BuiltInCheckerSuppliers.java | 2 + .../bugpatterns/CatchingUncheckedTest.java | 79 +++++++++++++++++ 3 files changed, 165 insertions(+) create mode 100644 core/src/main/java/com/google/errorprone/bugpatterns/CatchingUnchecked.java create mode 100644 core/src/test/java/com/google/errorprone/bugpatterns/CatchingUncheckedTest.java diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/CatchingUnchecked.java b/core/src/main/java/com/google/errorprone/bugpatterns/CatchingUnchecked.java new file mode 100644 index 00000000000..b276e0d25d8 --- /dev/null +++ b/core/src/main/java/com/google/errorprone/bugpatterns/CatchingUnchecked.java @@ -0,0 +1,84 @@ +/* + * Copyright 2020 The Error Prone Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.errorprone.bugpatterns; + +import static com.google.errorprone.matchers.Description.NO_MATCH; +import static com.google.errorprone.util.ASTHelpers.getType; +import static com.google.errorprone.util.ASTHelpers.isCheckedExceptionType; +import static com.google.errorprone.util.ASTHelpers.isSameType; +import static com.google.errorprone.util.ASTHelpers.isSubtype; + +import com.google.common.collect.ImmutableList; +import com.google.errorprone.BugPattern; +import com.google.errorprone.BugPattern.SeverityLevel; +import com.google.errorprone.VisitorState; +import com.google.errorprone.bugpatterns.BugChecker.TryTreeMatcher; +import com.google.errorprone.fixes.SuggestedFix; +import com.google.errorprone.matchers.Description; +import com.google.errorprone.util.ASTHelpers.ScanThrownTypes; +import com.sun.source.tree.CatchTree; +import com.sun.source.tree.TryTree; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.code.Type.UnionClassType; +import java.util.HashSet; +import java.util.Set; +import javax.annotation.Nullable; + +/** + * Flags code which catches {@link RuntimeException}s under the guise of catching {@link Exception}. + */ +@BugPattern( + name = "CatchingUnchecked", + summary = + "This catch block catches `Exception`, but can only catch unchecked exceptions. Consider" + + " catching RuntimeException (or something more specific) instead so it is more" + + " apparent that no checked exceptions are being handled.", + severity = SeverityLevel.WARNING) +public final class CatchingUnchecked extends BugChecker implements TryTreeMatcher { + + @Override + public Description matchTry(TryTree tree, VisitorState state) { + ScanThrownTypes scanner = new ScanThrownTypes(state); + scanner.scanResources(tree); + scanner.scan(tree.getBlock(), null); + Set thrownExceptions = new HashSet<>(scanner.getThrownTypes()); + for (CatchTree catchTree : tree.getCatches()) { + if (isSameType(getType(catchTree.getParameter()), state.getSymtab().exceptionType, state)) { + if (thrownExceptions.stream().noneMatch(t -> isCheckedExceptionType(t, state))) { + state.reportMatch( + describeMatch( + catchTree, + SuggestedFix.replace(catchTree.getParameter().getType(), "RuntimeException"))); + } + } + + ImmutableList caughtTypes = extractTypes(getType(catchTree.getParameter())); + thrownExceptions.removeIf(t -> caughtTypes.stream().anyMatch(ct -> isSubtype(t, ct, state))); + } + return NO_MATCH; + } + + private static ImmutableList extractTypes(@Nullable Type type) { + if (type == null) { + return ImmutableList.of(); + } + if (type.isUnion()) { + return ImmutableList.copyOf(((UnionClassType) type).getAlternativeTypes()); + } + return ImmutableList.of(type); + } +} diff --git a/core/src/main/java/com/google/errorprone/scanner/BuiltInCheckerSuppliers.java b/core/src/main/java/com/google/errorprone/scanner/BuiltInCheckerSuppliers.java index 4e49b5d3cfa..57d2130b9b8 100644 --- a/core/src/main/java/com/google/errorprone/scanner/BuiltInCheckerSuppliers.java +++ b/core/src/main/java/com/google/errorprone/scanner/BuiltInCheckerSuppliers.java @@ -56,6 +56,7 @@ import com.google.errorprone.bugpatterns.CanonicalDuration; import com.google.errorprone.bugpatterns.CatchAndPrintStackTrace; import com.google.errorprone.bugpatterns.CatchFail; +import com.google.errorprone.bugpatterns.CatchingUnchecked; import com.google.errorprone.bugpatterns.ChainedAssertionLosesContext; import com.google.errorprone.bugpatterns.ChainingConstructorIgnoresParameter; import com.google.errorprone.bugpatterns.CheckNotNullMultipleTimes; @@ -860,6 +861,7 @@ public static ScannerSupplier errorChecks() { BinderIdentityRestoredDangerously.class, // TODO: enable this by default. BindingToUnqualifiedCommonType.class, BooleanParameter.class, + CatchingUnchecked.class, CheckedExceptionNotThrown.class, ClassName.class, ClassNamedLikeTypeParameter.class, diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/CatchingUncheckedTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/CatchingUncheckedTest.java new file mode 100644 index 00000000000..ca3daa2f2a5 --- /dev/null +++ b/core/src/test/java/com/google/errorprone/bugpatterns/CatchingUncheckedTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2020 The Error Prone Authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.errorprone.bugpatterns; + +import com.google.errorprone.CompilationTestHelper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link CatchingUnchecked}. */ +@RunWith(JUnit4.class) +public final class CatchingUncheckedTest { + private final CompilationTestHelper helper = + CompilationTestHelper.newInstance(CatchingUnchecked.class, getClass()); + + @Test + public void positive() { + helper + .addSourceLines( + "Test.java", + "class Test {", + " void test() {", + " try {", + " this.hashCode();", + " // BUG: Diagnostic contains:", + " } catch (Exception e) {}", + " }", + "}") + .doTest(); + } + + @Test + public void positiveMultiCatch() { + helper + .addSourceLines( + "Test.java", + "import java.io.IOException;", + "class Test {", + " void test() {", + " try {", + " throw new IOException();", + " } catch (IOException e) {", + " // BUG: Diagnostic contains:", + " } catch (Exception e) {}", + " }", + "}") + .doTest(); + } + + @Test + public void negative() { + helper + .addSourceLines( + "Test.java", + "class Test {", + " void test() {", + " try {", + " throw new Exception();", + " } catch (Exception e) {", + " }", + " }", + "}") + .doTest(); + } +}