Tuesday, March 18, 2008

Find Null Pointer Exceptions Fast

Null Pointer Exceptions in Java are frustrating. They are the snipers of Java software development. NPEs can kill an application, well a poorly written one, and leave little trace of their cause.
A null pointer exception occurs when a method is invoked against an object that has a null value. Java seems to completely lose its mind and just print java.lang.NullPointerException and a class name. There's no stack trace and there's no line number. It's a bummer. You've been sniped by a NPE.
Like any good sniper, a NPE hides itself. You can tell the direction from where it came and that it happened, but that's about it.
The best way to deal with NPEs is to prevent them from happening. The way I try to do this is to assume that someone is going to pass a null value as one of the arguments and I assume that null could be returned by any one of my method invocations I'm pretty well covered.
Another trick I like to do is to flip values in equals methods, for example, I 'll go:
"value".equals(variable) instead of variable.equals("value")
by invoking the equals method on the String constant a NPE will never occur even if variable is null.
Luckily we all write awesome code so this never happens, but when we need to look at other people's code to find them I use the following technique. It's a divide and conquer technique that has served me well.
  1. Make it repeatable--find a way to repeat the use case consistently
  2. With your favorite debugger--use Eclipse if you don't have a favorite
  3. Step over each line until you hit your NPE
  4. Once you hit the NPE, put a break point on the line where the NPE occurred
  5. Uncheck the last iteration's last good break point.
  6. Rerun your use case
  7. Step into the line where the last NPE was thrown
  8. Repeat from step 3 until you find the cause
In a few iterations you will find the method and the line where the NPE is triggered.

No comments: