These rules provide some strict guidelines about throwing and catching exceptions.
This is dangerous because it casts too wide a net; it can catch things like OutOfMemoryError.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.strictexception.AvoidCatchingThrowable
Here's an example of code that would trigger this rule:
public class Foo { public void bar() { try { // do something } catch (Throwable th) { //Should not catch throwable th.printStackTrace(); } } }
It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.strictexception.ExceptionSignatureDeclaration
Here's an example of code that would trigger this rule:
public void methodThrowingException() throws Exception { }
Using Exceptions as flow control leads to GOTOish code.
This rule is defined by the following Java class: net.sourceforge.pmd.rules.design.ExceptionAsFlowControl
Here's an example of code that would trigger this rule:
public class Foo { void bar() { try { try { } catch (Exception e) { throw new WrapperException(e); // this is essentially a GOTO to the WrapperException catch block } } catch (WrapperException e) { // do some more stuff } } }
Code should never throw NPE under normal circumstances. A catch block may hide the original error, causing other more subtle errors in its wake.
This rule is defined by the following XPath expression:
//CatchStatement/FormalParameter/Type /ReferenceType/ClassOrInterfaceType[@Image='NullPointerException']
Here's an example of code that would trigger this rule:
public class Foo { void bar() { try { // do something } catch (NullPointerException npe) { } } }
Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead.
This rule is defined by the following XPath expression:
//AllocationExpression /ClassOrInterfaceType[ @Image='Throwable' or @Image='Exception' or @Image='Error' or @Image='RuntimeException']
Here's an example of code that would trigger this rule:
public class Foo { public void bar() throws Exception { throw new Exception(); } }
Avoid throwing a NullPointerException - it's confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer initiated exception.
This rule is defined by the following XPath expression:
//AllocationExpression/ClassOrInterfaceType[@Image='NullPointerException']
Here's an example of code that would trigger this rule:
public class Foo { void bar() { throw new NullPointerException(); } }