Is it okay to throw NullPointerException programmatically?

Viewed 100309

When there is a post-condition, that return value of a method must not be null, what can be done?

I could do

assert returnValue != null : "Not acceptable null value";

but assertions could be turned off!

So is it okay to do

if(returnValue==null)
      {
           throw new NullPointerException("return value is null at method AAA");
      }

?

Or is it better to use a user-defined exception (like NullReturnValueException ) for such a condition?

19 Answers

I agree with claim in the previous answers, that the NPE is bug in code and should not be thrown, but developer should fix unexpected null. However this state can be prevented most of time by tests.

The question was asked before 7 years, but now we have Optional in java 8 and this feature allow to prevent NPE.

The last one solution, which have on my mind is that you should check object on null and if it is equal, so throw your own exception with description of what happened.

Related