Null check error message as "is null" or "was null"
Asked Answered
S

4

11

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.

Sprayberry answered 11/6, 2010 at 11:31 Comment(4)
This is why I like const references in C++Chino
@Viktor Sehr Ah ha. So there is a reason to like const references in C++ - it's to avoid "is" vs "was" arguments.Gallicize
I'm slightly amused that the question of is vs. was feels important enough to anyone to even ask. I applaud that you want to write the best code you can, but with all due respect, maybe it's time to reexamine which code quality issues really matter.Qatar
@kevin-bourrillion, of course I realize that there are more important matters, I just wanted to hear some opinions on the matter. "maybe it's time to reexamine which code quality issues really matter.", that would be my next question ;)Biltong
L
15

Since the Exception is 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.Preconditions

Simple static methods to be called at the start of your own methods to verify correct arguments and state. This allows constructs such as

 if (count <= 0) {
   throw new IllegalArgumentException("must be positive: " + count);
 }

to be replaced with the more compact

 checkArgument(count > 0, "must be positive: %s", count);

More directly relevant here is that it has checkNotNull, which allows you to simply write:

  checkNotNull(username, "username should not be null");

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:

 // Awkward!
 checkArgument(count > 0, "is negative or zero: %s", count);
 checkNotNull(username, "username is null");

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 IllegalArgumentException vs NullPointerException

While your original code throws IllegalArgumentException on null arguments, Guava's Preconditions.checkNotNull throws NullPointerException instead.

This is in accordance with the guideline set by the API:

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

Additionally, here's a quote from Effective Java 2nd Edition: Item 60: Favor the use of standard exceptions:

Arguably, all erroneous method invocations boil down to an illegal argument or illegal state, but other exceptions are standardly used for certain kinds of illegal arguments and states. If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.

Lownecked answered 11/6, 2010 at 11:34 Comment(6)
@polygenelubricants, I am not sure if I agree on the Exception type question, but the first part of your answer is really good. Thanks!Biltong
"convention dictates" is not enough, using IllegalArgumentException for explicit checks and NPE for something the system does makes more sense to me, but it is good to know that there are other opinions ;)Biltong
The IAE vs. NPE debate for null arguments is age-old. There's a lot of sense to IAE, yet there's also the weight of many years of convention behind NPE. For Preconditions.checkNotNull we had to choose one or the other, and went with NPE. One advantage of NPE is that if your method changes from not explicitly checking it (just dereferencing it) to explicitly checking, or vice versa, the exception type doesn't change. Some people believe that you should always thoroughly check everything even if the same exception would be thrown two lines down, but I see this as waste of time and space.Qatar
(continued) the right place to be all "thorough" and "comprehensive" about this is in your unit tests, not the implementation code.Qatar
@Kevin, could you explain more about why you chose NPE? Also I'd like to know why these Preconditions.check* was introduced? To change the three line doing check + throw to a single line?Babarababassu
question 1: There's not much more to explain. As I said, there was the "weight of many years of convention" behind it, and our purpose was not to try to buck that convention but to streamline what our users were already doing. question 2: yes, that's about it.Qatar
Z
5

is null, since the argument is still null..

However, why not simply throw a NullPointerException without a message?

Zarzuela answered 11/6, 2010 at 11:32 Comment(9)
throwing NullPointerException without a message is not good, since it is not easy to separate from an accidental NullPointerExceptionBiltong
Throwing an exception without a message is often (if not always) a bad idea. Exception alone is rarely informative enough to understand what actually went wrong.Longrange
@Timo Westkämper 1 sec faster (:Longrange
Better yet: throw NPE with the name of the argument as the message. No need for verbosity but giving the argument name is a helpful information.Binkley
@Timo It's an NPE. Of course it is accidental! If you think adding the name of the argument is important, then your methods clearly have far too many parameters and you are using far too many nullables.Gallicize
Throwing a null pointer exception without a message means that a programmer MUST actually look at the source code to identify what caused the exception based on solely the line number. You as the programmer knows what is wrong - why not tell?Babarababassu
@tom-hawtin-tackline, why bother to write null checks which throw NPEs without a message, they look the same like NPEs from the system. When I write checks, I want to supply more information.Biltong
@Timo - if it makes you feel better to add a message, go for it. However, many experienced Java developers think that it adds no real value. The developer is going to need to look at the source code anyway.Pedicel
You have to take into account how often these messages get out of sync with the actual parameter names through refactorings. I've also seen cases where the parameter name cited doesn't even match the parameter name that's used in the interface the client is accessing the method through, so it's just purely confusing. Mostly, I strongly believe that at least 95% of the time this message isn't going to help the debugging programmer one bit. He'll look at the code; if there were multiple arguments it could have been, he'll look at the line of the stack trace... he'll generally be fine.Qatar
M
0

I would suggest saying

  if (userName == null) {
     throw new IllegalArgumentException("username == null");
   }

as this is so fatal that a programmer must look at it anyway. Referring the offending code snippet in the exception message is the concisest thing I can imagine.

Malapropism answered 11/6, 2010 at 12:32 Comment(3)
Interesting approach. Thanks for sharing! But fix the case for userName. (userName != username)Biltong
Hopefully an minor detail - unless, of course, you have both username and userName as parameters. :)Babarababassu
Well yes, but it looks confusing. But maybe this is also a "best practice" I am not aware of ;)Biltong
P
0

I would be inclined to write this:

public User getUser(String username) {
   if (username.length() == 0) {
       throw new IllegalArgumentException("username is empty");   
   }
   // ...
}

This kills two birds with one stone. First, it detects the case where user name is an empty string, which (for the sake of argument) I'm assuming is an error. Second, if the parameter is null attempting to dispatch the length call will give a NullPointerException.

For the record, the expected exception to throw for an unexpected null is NullPointerException. If your main reason for not using it is that NPE's typically don't have a message, code it like this:

public User getUser(String username){
   if (username == null){
       throw new NullPointerException("username is null");   
   }
   if (username.length() == 0) {
       throw new IllegalArgumentException("username is empty");   
   }
   // ...
}

Why use NPE's here? Because NPE's almost always indicate a different kind of problem to a other kinds of argument validation error; e.g. a field or array cell that has not been initialized or an "optional" value that is not being handled properly.

Finally to the question:

What is better : "is null" or "was null", and why?

This is a matter of opinion, but I would write "is null".

  • Because the message is reporting the state when the exception was thrown.
  • Because it is conventional to do it that way.
Pedicel answered 11/6, 2010 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.