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.
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:
.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.
See more on this question at Stackoverflow