Is it okay to throw NullPointerException programmatically?

I see no problem with throwing a NPE as early as possible before the JVM does it for you – in particular for null arguments. There seems to be some debate about this, but there are many examples in the Java SE libraries that does exactly this. I cannot see why NPE should be holy in the aspect that you are not able to throw it yourself.

However, I digress. This question is about something different. You are talking about a post-condition stating that the return value mustn’t be null. Surely null in this case would mean you have a bug inside the very method?

How would you even document this? “This method throws a NullPointerException if the return value unexpectedly is null”? Without explaining how this could happen? No, I would use an assertion here. Exceptions should be used for errors that can conceivably happen – not to cover things that can happen if there’s something wrong inside the method, because that does not help anybody.

Leave a Comment