How to trace a NullPointerException in a chain of getters

NPE is the most useless Exception in Java, period. It seems to be always lazily implemented and never tells exactly what caused it, even as simple as “class x.y.Z is null” would help a lot in debugging such cases.

Anyway, the only good way I’ve found to find the NPE thrower in these cases is the following kind of refactoring:

someObject.getSomething()
          .getSomethingElse()
          .getAnotherThing()
          .getYetAnotherObject()
          .getValue();

There you have it, now NPE points to correct line and thus correct method which threw the actual NPE. Not as elegant solution as I’d want it to be, but it works.

Leave a Comment