An issue is raised when code explicitly throws a NullPointerException using a throw statement.
Explicitly throwing a NullPointerException is almost always done to validate that a value is not null, typically with an
if statement followed by throw new NullPointerException(…). This is a verbose, hand-rolled way to perform a
null check that the Java standard library already provides. The rule therefore raises an issue on every explicit throw of a
NullPointerException, whether or not it is wrapped in a null check.
According to Effective Java, 3rd Edition, Item 72, while IllegalArgumentException might seem appropriate for null parameter
validation, Java conventions actually dictate that NullPointerException should be used for null values. Rather than throwing
it manually, you should use the standard validation utility that throws it for you: Objects.requireNonNull(), which has been available
since Java 7. This method:
if/throw block with a single, concise statementHand-written null checks reduce code maintainability and readability:
if/throw blocks add noise and make the actual logic of a method harder to followReplace manual NullPointerException throws with Objects.requireNonNull(). This method validates that an object is not
null and throws a NullPointerException if it is, using a concise and widely recognized idiom that follows Java
conventions.
public class UserService {
private String username;
public void setUsername(String username) {
if (username == null) {
throw new NullPointerException("username must not be null"); // Noncompliant
}
this.username = username;
}
}
public class UserService {
private String username;
public void setUsername(String username) {
this.username = Objects.requireNonNull(username, "username must not be null");
}
}