Affects PMD Version:
6.0.0
Rule:
AvoidThrowingNullPointerException
Description:
Currently, AvoidThrowingNullPointerException documentation says the following:
Example(s):Avoid throwing NullPointerExceptions. These are 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.
public class Foo { void bar() { throw new NullPointerException(); } }
This is one reason for activating the AvoidThrowingNullPointerException rule, true.
But a different - equally valid - reason for activating this rule would be the requirement to use the standard java.util.Objects.requireNonNull()
methods (available as of Java 1.7) instead of throwing a NullPointerException
manually.
In that case, the current documentation of AvoidThrowingNullPointerException would point the developer in the wrong direction by suggesting the use of IllegalArgumentException
instead of NullPointerException
.
I'd suggest to enhance the current documentation to point out both reasons and adding the Effective Java quote and examples below:
Example(s):Effective Java, 3rd Edition, Item 72: Favor the use of standard exceptions
Arguably, every erroneous method invocation boils down to an illegal
argument or state, but other exceptions are standardly used for certain kinds
of illegal arguments and states. If a caller passesnull
in some parameter
for whichnull
values are prohibited, convention dictates thatNullPointerException
be thrown rather thanIllegalArgumentException
.
public class Foo { private String exampleValue; void setExampleValue(String exampleValue) { if(exampleValue == null) { // manual check throw new NullPointerException("exampleValue must not be null!"); // manual throw } this.exampleValue = exampleValue; // assignment } } import java.util.Objects; public class Foo { private String exampleValue; void setExampleValue(String exampleValue) { // check, throw and assignment in a single standard call this.exampleValue = Objects.requireNonNull(exampleValue, "exampleValue must not be null!"); } }
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4