Do you choose to throw NPE ?

Well, NPE the NullPointerException is quite famous among Java programmers. It has a bad impression although, no one want to see this in console but everyone for sure see this more than once while programming.

The agenda of this blog is whether we should throw NPE explicitly or not. Throwing exception is always better than swallowing it with try-catch and even more empty catch block is the worst thing you could have in your program.

Throwing NPE explicitly is valid, however, if you are getting something null in method parameter than we have another suitable exception which can be much more suitable and that is IllegalArgumentException.

According to the documentation, NPE is about depicting the use of null reference in program which is detected at runtime by JVM. If you could detect whether something is null in your program and want to throw NPE you are not raising it because of illegal use of null reference and actually throwing it before that.

So, we should always throw IllegalArgumentException instead of NPE if possible. I believe you will always go with this exception instead of NPE, but kindly note that throwing NPE is not a bad practice at all. Ultimate goal is to make your system report immediately if anything goes wrong instead of just continuing the execution.

Here better not to create a custom exception for such cases. Because if we already have inbuilt exception than why to create our own, so, don’t reinvent the wheel.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s