Home / Java Patterns and Pitfalls     frequal.com

Debugging Null Pointer Exceptions

A common exception in Java is the Null Pointer Exception. By following a few simple steps, you can quickly narrow down the cause of a Null Pointer Exception (NPE), often to the exact spot in the code.

Reading the Stack Trace

The stack trace will tell you on which line of the program the problem occurred. If there are several chained exceptions, look for the one that clearly says "NullPointerException". For example:
Exception in thread "main" java.lang.NullPointerException
	at NPE.main(NPE.java:5)
This tells us that at line 5 in the file NPE.java, there was a NullPointerException.

Reading the Code

The great thing about this is that we are guaranteed that the null pointer was dereferenced on that line. All we have to find is objectName.methodName() or objectName.field on that line and we have found the source of the exception.

Line 5 of NPE.java in this case is:

    String str = obj.toString();
Since there is only one method invocation here, we know it is the cause. The toString method of obj was invoked. The reference obj must be null. At this point we can work backwards to find out why obj is null, and who was supposed to set it to a valid reference.

Multiple Dereferences

Sometimes there might be multiple object dereferences on a line. Consider if line 5 of NPE.java looked like this:
    System.out.println(obj.toString());
In this case there are 3 dereferences. However, examining them quickly determines that System is the System class and should never be null, and that System.out should never be null either. So again obj is the only possible culprit.

Simplifying Multiple Dereferences

If there are multiple potential dereferences on a line, it may also be a good reason to split the line into several smaller lines, each with one dereference. Then the NullPointerException line number will tell you exactly dereference is causing the problem.

One Tricky Case: Boxing and Unboxing

There is one final case where you can get a NullPointerException even when all of the objects being dereferenced are not null. Take this example:
  boolean flag = object.getBooleanFlag();
You are debugging and object is a valid reference (not null). Since that is the only dereference on the line, it looks like there can't be an NPE here. But if getBooleanFlag returns a Boolean object, Java tries to convert it to a boolean primitive. If getBooleanFlag returns null, then the conversion to the primitive value (called unboxing) fails with a NullPointerException.
Last modified on 11 May 2012 by AO

Copyright © 2024 Andrew Oliver