Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 325
Drew Avatar asked Apr 06 '10 16:04

Drew


People also ask

Is it good practice to catch NullPointerException?

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 type of exception is NullPointerException?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

Is a NullPointerException a syntax error?

There is no specific syntax for the Null pointer exception to specify as a run time error; it automatically arises and becomes visible for use.

Do not catch NullPointerException or any of its ancestors?

Catching NullPointerException may mask an underlying null dereference, degrade application performance, and result in code that is hard to understand and maintain. Likewise, catching RuntimeException , Exception , or Throwable may unintentionally trap other exception types and prevent them from being handled properly.


1 Answers

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.

like image 114
Joachim Sauer Avatar answered Oct 10 '22 06:10

Joachim Sauer