by BehindJava

Is it IllegalArgumentException or NullPointerException for a null parameter in Java

Home » java » Is it IllegalArgumentException or NullPointerException for a null parameter in Java

In this tutorial we are going to learn about using IllegalArgumentException or NullPointerException for a null parameter in Java.

Actually, the question of throwing IllegalArgumentException or NullPointerException is incomplete understanding of exception handling in Java.

In general, the rules are simple, and as follows:

  • Argument constraint violations must be indicated as fast as possible (-> fast fail), in order to avoid illegal states which are much harder to debug.
  • In case of an invalid null pointer for whatever reason, throw NullPointerException.
  • In case of an illegal array/collection index, throw ArrayIndexOutOfBounds.
  • In case of a negative array/collection size, throw NegativeArraySizeException.
  • In case of an illegal argument that is not covered by the above, and for which you don’t have another more specific exception type, throw IllegalArgumentException as a wastebasket.
  • On the other hand, in case of a constraint violation WITHIN A FIELD that could not be avoided by fast fail for some valid reason, catch and rethrow as IllegalStateException or a more specific checked exception. Never let pass the original NullPointerException, ArrayIndexOutOfBounds, etc in this case!

Advantage:

  • 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.