0

Running FindBug I got an alert on the following code:

public select(List<T> elements) {
    if (elements == null)
        throw new NullPointerException();

With the following explanation:

Avoid throwing a NullPointerException - it's confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer-initiated exception.

However, I always thought throwing null pointer exceptions for null parameters was correct. And I look for example at the implementation of ArrayList, I can find something similar:

    public boolean tryAdvance(Consumer<? super E> action) {
        if (action == null)
            throw new NullPointerException();

So, is it really incorrect? And why? Why is Findbug telling me that is wrong?

user1883212
  • 7,539
  • 11
  • 46
  • 82
  • Findbugs, very astutely tells you why not to throw NullPointerExceptions. you should probably listen to it. Throw an IllegalArgumentException instead. – Shaun Wild Jul 08 '16 at 15:25
  • 1
    @AlanTuning That's very subjective and I would disagree. The standard practice is to throw a NPE - see for example the JDK (`Objects.requireNonNull` throws NPE) or guava (`Preconditions.checkNotNull` also throws a NPE)... – assylias Jul 08 '16 at 15:28
  • @assylias It's a contentious subject, [this question](http://stackoverflow.com/questions/3322638/is-it-okay-to-throw-nullpointerexception-programatically) for example shows that. – Shaun Wild Jul 08 '16 at 15:30
  • @AlanTuning You will note the date on those posts - I think the introduction of requireNonNull in Java 7 is a pretty strong precedent that was not available at the time. – assylias Jul 08 '16 at 15:33

0 Answers0