Hectoret Hectoret - 3 years ago 131
Java Question

Find out what variable is throwing a NullPointerException programmatically

I know I can find out if a variable is null in Java using these techniques:


  • if
    (var==null)
    -> too much work

  • try { ... } catch (NullPointerException e) { ...}
    -> it tells me what line is throwing the exception

  • using the debugger -> by hand, too slow



Consider this line of code:

if (this.superSL.items.get(name).getSource().compareTo(VIsualShoppingList.Source_EXTRA)==0) {


I would like to know if there's a generic way to find out programatically what variable (not just the line) is throwing the NullPointerException in a certain area of code. In the example, knowing that

Answer Source

Since it's possible to cause a null pointer exception without even involving a variable:

throw new NullPointerException();

I would have to say that there is no generic way to pin down a null pointer exception to a specific variable.

Your best bet would be to put as few as possible statements on each line so that it becomes obvious what caused the null pointer exception. Consider refactoring your code in the question to look something like this:

List items = this.superSL.items;
String name = items.get(name);
String source = name.getSource();
if (source.compareTo(VIsualShoppingList.Source_EXTRA) == 0)  {
    // ...
}

It's more lines of code to be sure. But it's also more readable and more maintainable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download