Is Catching a Null Pointer Exception a Code Smell?
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?
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.
I can think of exactly one use for ever catching a NullPointerException
:
catch (NullPointerException) {
ApplyPainfulElectricShockToProgrammer();
}