[java]AvoidCatchingThrowable can not detect the case: catch (java.lang.Throwable t)

This commit is contained in:
Mykhailo Palahuta
2020-07-28 17:11:14 +03:00
parent 25405eb870
commit 91b942b1dc
2 changed files with 23 additions and 8 deletions

View File

@ -5,8 +5,6 @@
package net.sourceforge.pmd.lang.java.rule.errorprone;
import net.sourceforge.pmd.lang.java.ast.ASTCatchStatement;
import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceType;
import net.sourceforge.pmd.lang.java.ast.ASTType;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
/**
@ -18,12 +16,12 @@ import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
public class AvoidCatchingThrowableRule extends AbstractJavaRule {
@Override
public Object visit(ASTCatchStatement node, Object data) {
ASTType type = node.getFirstDescendantOfType(ASTType.class);
ASTClassOrInterfaceType name = type.getFirstDescendantOfType(ASTClassOrInterfaceType.class);
if (name.hasImageEqualTo("Throwable")) {
addViolation(data, name);
public Object visit(ASTCatchStatement catchStatement, Object data) {
for (Class<? extends Exception> caughtException : catchStatement.getCaughtExceptionTypes()) {
if (Throwable.class.equals(caughtException)) {
addViolation(data, catchStatement);
}
}
return super.visit(node, data);
return super.visit(catchStatement, data);
}
}

View File

@ -24,6 +24,23 @@ public class Foo {
void foo() {
try {} catch (RuntimeException t) {}
}
}
]]></code>
</test-code>
<test-code>
<description>full class name false-negative test</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>5</expected-linenumbers>
<code><![CDATA[
public class Foo {
public void bar() {
try {
Foo.class.isAssignableFrom(null);
} catch(java.lang.Throwable e) {
e.printStackTrace();
}
}
}
]]></code>
</test-code>