Java IllegalArgumentException VS NullPointerException

Which exception should be thrown when a null argument is passed on to a method that does not accept null?
public static String strictConcat(String s1, String s2) {
if (s1 == null || s2 == null) {
throw new IllegalArgumentException("arguments may not be null");
}
return s1 + s2;
}

If you have used Java for a little while, you probably asked yourself this question at least once.

The JDK seems to let NPE explode — yet not always — , but a lot of developers use IAE, as is seems a legitimate thing to do too. So what should we do?

RTFM

Let’s look at the official JavaDoc first:

  • IllegalArgumentException: Thrown to indicate that a method has been passed an illegal or inappropriate argument.
  • NullPointerException: the doc contains a list of situations other than our problem, and then at the end: “Applications should throw instances of this class to indicate other illegal uses of the null object.

If we just rely on the documentation, the descriptions simply overlap: IAE concerns all kinds of wrong arguments, while NPE concerns all kinds of misuse of null.

We should have an exception representing the intersection of these 2, a misuse of null as an argument: NullArgumentException (or something like that), which would inherit from one of the above (the same debate would apply there), and would specifically fit our situation, but we don’t have that exception.

From a semantic point of view, both IAE and NPE seem equally suitable for the situation, hence the holy war.

In my opinion, from the docs, I already favor IAE because our situation clearly fits the main description, while the list of NPE-suitable situations does not directly include ours, which is merely suggested at the end. Since the documentation does not allow us to clearly choose one over the other, let’s focus on the usage.

What matters is what happens in practice

Here, I don’t mean “what is currently mostly used” (The French humorist Coluche said “Just because they are a lot to be wrong does not make them right”). I know that the JDK uses both of them, but I won’t elaborate on that. Actually, what I’m asking is:

What is your first diagnostic when you see IAE and when you see NPE thrown from some third party code?

As far as I’m concerned, when I see an IAE, I immediately assume that I have passed something wrong on to the first method of the stack trace, and I go check its arguments. When I see an NPE, I think “Something might be wrong in that lib, a null pointer was dereferenced inside”, and I go to the code of the function (if I can) to investigate.

That’s how I made my choice: I use IllegalArgumentException because I don’t want to make programmers look inside a function they didn’t write just to realize what they did wrong when calling it.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.