When doing null checks in Java code, and you throw IllegalArgumentExceptions for null values, what kind of message template do you use?
We tend to use something like this
public User getUser(String username){
if (username == null){
throw new IllegalArgumentException("username is null");
}
// ...
}
What is better : “is null” or “was null”, and why?
For me “is null” feels more natural.
Since the
Exceptionis thrown due to a failed precondition check, I think rather than simply stating a fact, you should state the requirement that was violated.That is, instead of saying
"username is null", say"username should not be null".On using libraries for precondition checks
As a tip, you can use one of the many libraries designed to facilitate precondition checks. Many code in Guava uses
com.google.common.base.PreconditionsMore directly relevant here is that it has
checkNotNull, which allows you to simply write:Note how naturally the above code reads, with the detailed message explicitly stating the requirement that was violated.
The alternative of stating facts is more awkward:
Moreover, this is also potentially less useful, since the client may already be aware of the fact, and the exception doesn’t help them figure out what the actual requirements are.
On
IllegalArgumentExceptionvsNullPointerExceptionWhile your original code throws
IllegalArgumentExceptiononnullarguments, Guava’sPreconditions.checkNotNullthrowsNullPointerExceptioninstead.This is in accordance with the guideline set by the API:
Additionally, here’s a quote from Effective Java 2nd Edition: Item 60: Favor the use of standard exceptions: