Is Catching a Null Pointer Exception a Code Smell?

21,120

Solution 1

Yes, catching any RuntimeException is almost always a code smell. The C2 Wiki seems to agree.

An exception would probably be some specially defensive pieces of code which run pretty much random code from other modules. Examples for such defensive structures would be the EDT, ThreadPools/Executors and plugin system.

Solution 2

I can think of exactly one use for ever catching a NullPointerException:

catch (NullPointerException) {
    ApplyPainfulElectricShockToProgrammer();
}

Solution 3

I have had to catch nullpointer exception sometimes because of a bug in third part library. The library we used threw that exception, and it was nothing we could do about it.

In that case it is OK to catch it, otherwise not.

Solution 4

It depends.

How experienced this co-worker is? Is he doing this for ignorance/laziness or is there a real good reason for that? ( like this is the main thread above everything else and should never ever die? )

90% of the times catching a runtime exception is wrong, 99% catching a NullPointerException is wrong ( if the reason is "I was getting a lot of them..." then the whole programmer is wrong and you should look take care for the rest of the code he's doing )

But under some circumstances catching a NullPointerException may be acceptable.

Solution 5

In general, I think it is a code smell; it seems to me that defensive checks are better. I would extend that to cover most unchecked exceptions, except in event loops, etc. that want to catch all errors for reporting/logging.

The exception I can think of would be around a call to a library that can't be modified and which may generate a null pointer exception in response to some assertion failure that is difficult to proactively check.

Share:
21,120
Drew
Author by

Drew

Updated on July 09, 2022

Comments

  • Drew
    Drew almost 2 years

    Recently a co-worker of mine wrote in some code to catch a null pointer exception around an entire method, and return a single result. I pointed out how there could've been any number of reasons for the null pointer, so we changed it to a defensive check for the one result.

    However, catching NullPointerException just seemed wrong to me. In my mind, Null pointer exceptions are the result of bad code and not to be an expected exception in the system.

    Are there any cases where it makes sense to catch a null pointer exception?