Never throw a NullPointerException. Ever.
NullPointerExceptions (NPEs) happen in Java. They indicate that the VM tried to de-reference a null - value. And that's OK. But it is not OK to write code like this:
if(someVariable == null) {
throw new NullPointerException("The value of \"someVariable" must not be null");
}
It is not OK to write code like this for 3 reasons:
- As I said before, the NPE indicates that some part of the program tried to de-reference a null value. This did not happen here.
- The exception class you use should indicate what happened. Otherwise we would have only 2 Exception classes in Java: Exception and RuntimeException.
- NPEs indicate a programming error and are quite useful to find bugs. You compromise this when you throw them for "normal" errors.
As for the second point: I can think of two reasons why the null value is not allowed here. The first would be that null is an illegal value for an argument of your method. Use "IllegalArgumentException" in this case. The other reason is that a null value would cause an illegal program state. In this case you can use "IllegalStateException". If both scenarios do not feel right for you, create your own exception class.
(Just another rant. Everything IMHO. This post is somewhat related to Exception Abuse. And yes, there is a reason why I wrote this.)





