Sunday, May 8, 2011

How to debug: java.lang.NullPointerException

JVM throws NullPointerException whenever it tries to execute an expression which ultimately evaluates to:
null.someMethod();
Here is a short code snippet that demonstrates a scenario:
class NullPointerExceptionDemo
{
                public static void main(String args[])
                {
                                String nullString = null;
                                String nonNullString="This is not a null string";                   
                                if(nullString.equals(nonNullString))
                                {
                                                System.out.println("This will not execute");
                                }
                               
                }
}

The above code will compile fine. The compiler won’t complain about the code as it is syntactically fine. While executing the code, JVM will throw the NullPointerException. The output will be something like this:


Exception in thread "main" java.lang.NullPointerException
        at NullPointerExceptionDemo.main(NullPointerExceptionDemo.java:7)
Press any key to continue...


This is because the expression :

nullString.equals(nonNullString)

evaluates to :

null.equals("This is not a null string")

While troublesooting this type of exceptions it is important to get the stack trace of the exception and then find where a null value is being assigned to the reference variable on which we are invoking some method. The stack trace of an exception can be obtained by calling “printStackTrace()” method from catch block. This is useful technique of troubleshooting NullPointerException when there is a mess of method calls, when it is very difficult to know where the null value is being assigned.

Here is an example code snippet that shows how to use the stack trace to debug the NullPointerException problem:



On execution the output will be like this:


java.lang.NullPointerException
        at NullPointerExceptionDemo1.method3(NullPointerExceptionDemo1.java:25)
        at NullPointerExceptionDemo1.method2(NullPointerExceptionDemo1.java:20)
        at NullPointerExceptionDemo1.method1(NullPointerExceptionDemo1.java:16)
        at NullPointerExceptionDemo1.main(NullPointerExceptionDemo1.java:8)
Press any key to continue...


This says that the exception was first thrown at line 25 from method3, where it was not handled so thrown up to the caller method : method2. In method2, the exception was not handled here. It was line 20 that caused exception for method2. Again it was thrown to method1 at line 16 and again up to main at line 8. In main method it was handled.

Thus the stack trace tells us the root where the exception was thrown and how it was thrown up and where it was handled




No comments:

Post a Comment