Search code examples
javajvmbytecode

Java StackTrace does not show where is the actual null in the line


The following Exception:

Exception in thread "main" java.lang.NullPointerException
at javaapplication7.App.main(App.java:8)
Java Result: 1

thrown from code:

Object o = n1.getObj().getObj().getObj().getObj();

So from the stack trace it is not clear which element was actually null. Is there a method to find it out without debugging? Maybe some other JVM will do?


Solution

  • No, you can't figure out which of the callees in

    Object o = obj.getObj().getObj().getObj().getObj();
    

    causes the NullPointerException by looking at the stack trace. It is often recommended to format your code as

    Object o = obj.getObj()
                  .getObj()
                  .getObj()
                  .getObj();
    

    for this reason.