NullPointerException vs IllegalArgumentException

There has been lots of discussion going on for a very long time weather to use NPE or IAE when a null is passed when a non-null object is expected as an method/constructor argument.

After developing java applications for quite sometime, I have observed that when one sees a NPE in the log file, it usually means some serious bug which should be dealt with.  I strongly think that NPE should only ever be thrown by the JVM when it try to access some properties/methods of a null object (hey did you notice, it is called Null Pointer Exception where pointer means trying to access a property or method on null).

However javadoc for NPE allows applications to throw NPE in other subjective scenarios, which led to misuse of it.

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

To move on, if only all developers follow the convention to use only IAE and leave the NPE to the JVM, life would far better for the troubleshooters :)

So next time you validating the constructor/method parameter, forget NPE and use IAE.

    public void doSomething(String anything) {
        if (anything == null) {
            throw new IllegalAccessError("Parameter anything is null");
        }
    }

0 Responses to “NullPointerException vs IllegalArgumentException”


  1. No Comments

Leave a Reply