Why should one use Objects.requireNonNull()?

Why should one use Objects.requireNonNull() ?

I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull(), which internally throws NullPointerException if the given object (argument) is null.

public static <T> T requireNonNull(T obj) {
    if (obj == null)
        throw new NullPointerException();
    return obj;
}

But NullPointerException will be thrown anyway if a null object is dereferenced. So, why should one do this extra null check and throw NullPointerException?

One obvious answer (or benefit) is that it makes code more readable and I agree. I'm keen to know any other reasons for using Objects.requireNonNull() in the beginning of the method.

Jon Skeet
people
quotationmark

But NullPointerException will be thrown anyway if a null object is dereferenced. So, why should one do this extra null check and throw NullPointerException?

It means you detect the problem immediately and reliably.

Consider:

  • The reference may not be used until later in the method, after your code has already performed some side-effects
  • The reference may not be dereferenced in this method at all
    • It could be passed to completely different code (i.e. cause and error are far apart in code space)
    • It could be used much later (i.e. cause and error are far apart in time)
  • It may be used somewhere that a null reference is valid, but has an unintended effect

.NET makes this better by separating NullReferenceException ("you dereferenced a null value") from ArgumentNullException ("you shouldn't have passed in null as an argument - and it was for this parameter). I wish Java did the same thing, but even with just a NullPointerException, it's still much easier to fix code if the error is thrown at the earliest point at which it can be detected.

people

See more on this question at Stackoverflow