NullPointerException
occurs when you try to dereference a null
, not when you just create or have one. Stack trace contains the line, and that's as good as it gets, and JVM does not really know where the null
came from, it does not keep track of such things when it tries to churn through the bytecode as fast as possible.
If you have trouble debugging such situations, you can always split expression and use temp variable:
String tmp = myObj.getSomething();
String result = tmp.substring(1);
If 1st line above throws NullPointerException (with stack trace showing it came from that line, not from inside myObj.getSomething()
), you know myObj was null. If 2nd line throws NullPointerException, you know tmp
was null, ie myObj.getSomething()
returned null. If you then notice that myObj.getSomething()
may in fact return null in normal situation, you can then add if (tmp != null) { ... } else { ... }
kind of code there.