Interesting strategy for handling Null Pointer Exceptions


I was talking to a senior java developer sometime back. We were discussing some code base and we can ame across a interresting snippet:

try {
    myVar1.getMyVar2().getMyVar3().doSomething();
} catch (NullPointerException npe) {
}

I was amazed to see this line of code and I immediately asked why was this written like this. The experienced java developer said that he put in this line to inorder to fix a NPE occurance QA had reported. upon asking why not put in a simple null check around the variable which was null instead of having a try catach block he said this strategy had several advantages the most attractive of them was then he didn’t have to debug and check the variable which was null. This guarded against all any of the variables involved in the code against NPEs.

I think thisd is not at all a good approach because you are not actually fixing the problem but only hiding its occurance. In some cases putting in a null check is analogus to catching the NPE. I think a proper fix should be to find out the root cause of why we had a nbull reference and fix iut from there. There are sometimes race conditions in the code that can cause these null references and hiding the occurance like this can cauise all sort of problems in the long run.

Advertisements
Interesting strategy for handling Null Pointer Exceptions

One thought on “Interesting strategy for handling Null Pointer Exceptions

  1. V says:

    I entirely agree. I have seen code where RuntimeException is actually caught since the developer did not want to catch NPE and ArrayIndexOutofBounds seperately. I tried very hard to explain these exceptions where unchecked exceptions for a reason and catching them like this, is leaving the real problem unfixed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s