I was all in favour of throwing IllegalArgumentException
for null parameters, until today, when I noticed the java.util.Objects.requireNonNull
method in Java 7. With that method, instead of doing:
if (param == null) {
throw new IllegalArgumentException("param cannot be null.");
}
you can do:
Objects.requireNonNull(param);
and it will throw a NullPointerException
if the parameter you pass it is null
.
Given that that method is right bang in the middle of java.util
I take its existence to be a pretty strong indication that throwing NullPointerException
is "the Java way of doing things".
I think I'm decided at any rate.
Note that the arguments about hard debugging are bogus because you can of course provide a message to NullPointerException
saying what was null and why it shouldn't be null. Just like with IllegalArgumentException
.
One added advantage of NullPointerException
is that, in highly performance critical code, you could dispense with an explicit check for null (and a NullPointerException
with a friendly error message), and just rely on the NullPointerException
you'll get automatically when you call a method on the null parameter. Provided you call a method quickly (i.e. fail fast), then you have essentially the same effect, just not quite as user friendly for the developer. Most times it's probably better to check explicitly and throw with a useful message to indicate which parameter was null, but it's nice to have the option of changing that if performance dictates without breaking the published contract of the method/constructor.