Avoiding Nullpointerexception in Java

Avoiding NullPointerException in Java

This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.

To put this another way, there are two instances where null checking comes up:

  1. Where null is a valid response in terms of the contract; and

  2. Where it isn't a valid response.

(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)

"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.

public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}

It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.

Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();

Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.

(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.

If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.

With non-collections it might be harder. Consider this as an example: if you have these interfaces:

public interface Action {
void doSomething();
}

public interface Parser {
Action findAction(String userInput);
}

where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.

An alternative solution is to never return null and instead use the Null Object pattern:

public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};

public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}

Compare:

Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}

to

ParserFactory.getParser().findAction(someInput).doSomething();

which is a much better design because it leads to more concise code.

That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.

try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}

Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.

public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}

How to avoid null pointer exception in java

Other than catching the error, if you are going to work with something which might be null, you might want to throw in null checks.

What you could do to reduce the chances of having to make null checks, would be to never return null from your methods, unless it is really necessary, for instance:

public IList<String> getUserNames()
{
//No usernames found...
return new ArrayList<String>();

//As opposed to returning null
return null;
}

By returning the empty list, a call to the above code would result into something like so: for(String name : this.getUserNames()) {...}. If no user names where found, the loop will not execute.

If on the other hand, you return null, you would need to do something like so:

List<String> userNames = this.getUsernames();
if(userNames != null)
for(String userName : userNames) {....}

What is a NullPointerException, and how do I fix it?

There are two overarching types of variables in Java:

  1. Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.

  2. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.

Consider the following code where you declare a variable of primitive type int and don't initialize it:

int x;
int y = x + x;

These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.

Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).

If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.

The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.

Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

public void doSomething(SomeObject obj) {
// Do something to obj, assumes obj is not null
obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

doSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

/**
* @param obj An optional foo for ____. May be null, in which case
* the result will be ____.
*/
public void doSomething(SomeObject obj) {
if(obj == null) {
// Do something
} else {
// Do something else
}
}

Finally, How to pinpoint the exception & cause using Stack Trace

What methods/tools can be used to determine the cause so that you stop
the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE.
Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

How to avoid NullpointerException without null check in java

You can avoid many null checks by using Yoda Expressions, for example

if ("Hello".equals(str))

"Hello", as a literal, is never null and the built-in equals method will check str for null-ness. The alternative str.equals("Hello") would require you to check str first.

Some folk find them obfuscating, and it's not always possible to arrange your syntax accordingly.

How do I avoid a NullPointerException when stopping and starting a Clip in Java?

Your problem is on this line:

            Clip clip = AudioSystem.getClip();

This is creating a local variable, and not setting the clip to the member variable you are using below.

Instead, try:

            clip = AudioSystem.getClip();

How do I avoid this NullPointerException in my custom linked list class?

It seems you are assigning null values to them as well, but the checks aren't complete. I would suggest you throw a NullPointerException for you to be able to handle it yourself e.g. inside a try catch block. This will prepare you for scenarios if the values are null then do this instead.

try {
// Your usual code here
} catch(NullPointerException e) {
// Do something if it hit an NPE
}


Related Topics



Leave a reply



Submit