Luke De Feo
Luke De Feo

Reputation: 2165

Throwing a NPE at the start of method for error checking

So im preparing for interviews and in one of Gayle Laakmans career Cup videos a guy is writing a simple method that takes in an array and does something with it. She mentions his lack of error checking so he adds in this line like so:

public int max(int[] array) {
    if (array == null)
        throw new NullPointerException();

    //method body

}

Is it correct to manually throw a NPE exception like this, this exception will get thrown anyway in the method body as it will use the array reference at some point.

A possible advantage to this i can see is that it separates input invalidation from the method logic being invalid and somehow creating a null reference. Otherwise it is a little confusing and maybe IllegalArgumentException would work better?

Upvotes: 1

Views: 228

Answers (2)

Jan
Jan

Reputation: 2342

Also have a look at java's own utility class java.util.Objects:

public static <T> T requireNonNull(T obj,
               String message)

Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:

 public Foo(Bar bar, Baz baz) {
     this.bar = Objects.requireNonNull(bar, "bar must not be null");
     this.baz = Objects.requireNonNull(baz, "baz must not be null");
 }
  • Type Parameters:
    T - the type of the reference

  • Parameters:
    obj - the object reference to check for nullity
    message - detail message to be used in the event that a NullPointerException is thrown

  • Returns:
    obj if not null

  • Throws:
    NullPointerException - if obj is null

from https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html

Conclusion

Whether or not you use this utility class is another question, but it definitely shows, that the team behind the Java language intended to use NullPointerException for these purposes.

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 405745

There's nothing wrong with throwing NullPointerException as soon as you enter the method instead of waiting to detect it after some processing has already been done. If the method is going to fail, it might as well fail fast.

Joshua Bloch's Effective Java recommends throwing NullPointerException over IllegalArgumentException in this situation (Item 60: Favor the use of standard exceptions).

If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.

IllegalArgumentException should be thrown when an illegal non-null value is passed in.

Upvotes: 3

Related Questions