What is the purpose of Objects#requireNonNull
A good principle when writing software is to catch errors as early as possible. The quicker you notice, for example, a bad value such as null
being passed to a method, the easier it is to find out the cause and fix the problem.
If you pass null
to a method that is not supposed to receive null
, a NullPointerException
will probably happen somewhere, as you already noticed. However, the exception might not happen until a few methods further down, and when it happens somewhere deep down, it will be more difficult to find the exact source of the error.
So, it's better when methods check their arguments up front and throw an exception as soon as they find an invalid value such as null
.
edit - About the one-parameter version: even though you won't provide an error message, checking arguments and throwing an exception early will be more useful than letting the null
pass down until an exception happens somewhere deeper down. The stack trace will point to the line where you used Objects.requireNonNull(...)
and it should be obvious to you as a developer that that means you're not supposed to pass null
. When you let a NullPointerException
happen implicitly you don't know if the original programmer had the intent that the variable should not be null
.
It is a utility method. Just a shortcut! (shortcut designers have their ways of doing their shortcut style).
Why throwing in the first place? Security and Debugging.
- Security: to not allow any illegal value in a sensitive place. (makes inner algorithm more sure about what are they doing and what are they having).
- Debugging: for the program to die fast when something unexpected happens.