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
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.