Merge pull request #3715 from oowekyala:update-AvoidCatchingGenericException

[java] Update rule AvoidCatchingGenericException #3715

* pr-3715:
  [java] AvoidCatchingGenericException - consider multi-catch
  Update rule AvoidCatchingGenericException
This commit is contained in:
Andreas Dangel
2022-01-14 08:32:52 +01:00
4 changed files with 35 additions and 6 deletions

View File

@@ -119,7 +119,7 @@
<!-- design.xml -->
<rule ref="category/java/design.xml/AbstractClassWithoutAnyMethod"/>
<!-- <rule ref="category/java/design.xml/AvoidCatchingGenericException"/> -->
<rule ref="category/java/design.xml/AvoidCatchingGenericException"/>
<!-- <rule ref="category/java/design.xml/AvoidDeeplyNestedIfStmts"/> -->
<rule ref="category/java/design.xml/AvoidRethrowingException"/>
<!-- <rule ref="category/java/design.xml/AvoidThrowingNewInstanceOfSameException"/> -->

View File

@@ -57,10 +57,10 @@ Avoid catching generic exceptions such as NullPointerException, RuntimeException
<property name="xpath">
<value>
<![CDATA[
//CatchStatement/FormalParameter/Type/ReferenceType/ClassOrInterfaceType[
@Image='NullPointerException' or
@Image='Exception' or
@Image='RuntimeException']
//CatchParameter//ClassOrInterfaceType[
pmd-java:typeIsExactly('java.lang.NullPointerException') or
pmd-java:typeIsExactly('java.lang.Exception') or
pmd-java:typeIsExactly('java.lang.RuntimeException')]
]]>
</value>
</property>

View File

@@ -6,7 +6,6 @@ package net.sourceforge.pmd.lang.java.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
@org.junit.Ignore("Rule has not been updated yet")
public class AvoidCatchingGenericExceptionTest extends PmdRuleTst {
// no additional unit tests
}

View File

@@ -31,6 +31,21 @@ public class Foo {
}
}
}
class FooException extends RuntimeException {}
]]></code>
</test-code>
<test-code>
<description>catching subclass of NPE, ok</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class Foo {
void bar() {
try {
} catch (FooException e) {
}
}
}
class FooException extends NullPointerException {}
]]></code>
</test-code>
@@ -45,4 +60,19 @@ public class Foo {
}
]]></code>
</test-code>
<test-code>
<description>failure case with multi-catch</description>
<expected-problems>2</expected-problems>
<code><![CDATA[
public class Foo {
void bar() {
try {
} catch (NullPointerException | RuntimeException | FooException e) {
}
}
}
class FooException extends Exception {}
]]></code>
</test-code>
</test-data>