An issue is raised when code explicitly throws a NullPointerException using a throw statement.

Why is this an issue?

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:

What is the potential impact?

Hand-written null checks reduce code maintainability and readability:

How to fix it

Replace 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.

Code examples

Noncompliant code example

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;
    }
}

Compliant solution

public class UserService {
    private String username;

    public void setUsername(String username) {
        this.username = Objects.requireNonNull(username, "username must not be null");
    }
}

Resources

Documentation

Articles & blog posts

Standards