I know I can find out if a variable is null in Java using these techniques:
(var==null)
-> too much worktry { ... } catch (NullPointerException e) { ...}
-> it tells me what line is throwing the exceptionConsider 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
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.
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.
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. 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With