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 is
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
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.
One Tricky Case: Boxing and UnboxingThere 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
Copyright © 2016 Andrew Oliver