Is it okay to throw NullPointerException programmatically? [closed]

I would recommend you never throw NullPointerException by yourself.

The main reason not to do this, as Thorbjørn Ravn Andersen says in a comment below, is that you don’t wan’t to mix ‘real, bad NPEs’ with NPEs thrown intentionally.

So, until you’re confident that you’re able to recognize ‘valid’ NPE, I’d recommend to use IllegalArgumentException when you want to tell to your API user that null is not a valid argument value. Your method’s behavior when illegal null-parameter passed should be documented.

Another (more modern imho) option is to use @NotNull annotation near the argument.
Here is an article about using @NotNull annotation.

As I mentioned earlier, there can also be cases, when throwing NPE will not be confusing either to you or to your teammates: NPE cause should be clear and recognizable.

For instance, if you use some library with preconditions module, like Guava, then I find using checkNotNull()-like methods is a preferable way to deal with illegally-passed nulls.

checkNotNull(arg, msg) throws NPE, but from the stacktrace it’s quite clear, that it was produced by Preconditions.checkNotNull() and thus it’s not an unknown bug but rather expected behavior.

Leave a Comment