Debugging Null Pointer ExceptionsA 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 TraceThe 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 CodeThe great thing about this is that we are guaranteed that the null pointer was dereferenced on that line. All we have to find isobjectName.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 DereferencesSometimes 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 DereferencesIf 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.Copyright © 2009 Andrew Oliver |