Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 487
Hectoret Avatar asked Apr 19 '10 13:04

Hectoret


People also ask

How do I check NullPointerException?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

In which case the NullPointerException will be thrown?

Class NullPointerException Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object.

Can you catch a NullPointerException?

It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.

What causes NullPointerException in Java?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.


1 Answers

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.

like image 105
Asaph Avatar answered Oct 07 '22 18:10

Asaph