Exception Handling – Is it Acceptable to Use Try Catch for Null Pointer Exceptions?

exception handling

There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

Best Answer

If you're using third party code that is returning null, it's much better to check the return value.

ThirdPartyValue thirdPartyValue = thirdParty.getValue();
if (null == thirdPartyValue) {
    ...
}

Edit: Java 8 is out! This should now be

Optional<ThirdPartyValue> thirdPartyValue = Optional.ofNullable(thirdParty.getValue());

A NullPointerException is insidious and misleading, because it means you have an error somewhere else, where a variable was set to null without you expecting it to be.

I repeat, the bug isn't where the NullPointerException was thrown, the bug is earlier in your code, where a variable was set to null without you expecting it to be.

Catching the NullPointerException means you're hiding or excusing the actual bug.

In your own code, it is much better to do away with null whereever possible, and for that matter, also mutable variables.

If you get an exception, don't catch it and return null, instead wrap and rethrow the exception.

If you have a method that should sometimes not return a value, you could return an empty Collection, or an Optional, which is new in Java 8.

If you never set a variable to null you can never have an unexpected null.

Don't allow null parameters:

public void method(A param1, B param2, C param3) {
    requireNonNull(param1, param2, param3);
    ...
}

public static void requireNonNull(Object... parameters) {
    Stream.of(parameters).forEach(Objects::requireNonNull);
}

Avoid creating "result" variables that are temporarily null:

Instead of:

public Result method() {
    Result result = null;    // <- this smells
    try {
        result = ...;
    } catch (SomeException e) {
        LOGGER.log(Level.WARNING, "Exception "+e.getMessage(), e);
    }
    return result;
}

you should:

public Result method() {
    try {
        return ...;
    } catch (SomeException e) {
        throw new MyPossiblyRuntimeException(e);
    }
}

Sooner or later you will start to see usage of null (and mutable variables) as a code smell.

I'm sure you can come up with other smart ways to avoid null, be creative!

tl;dr: NullPointerException should never be thrown in the first place, so don't catch it, because that means you're hiding the actual bug.