Is it more Java-thonic to throw an exception or return null?

error-handling, java, json, nullpointerexception

Solution

This is an esoteric question!

The conventional wisdom is this:-

Don't use exceptions for control flow. Exceptions should be left for when something exceptional happens

This implies returning a NULL and checking for it. i.e. choice (1)

But here is an interesting discussion on this very subject in the context of the Java language.

In a nutshell, as Java's exception system is so flexible, sometimes throwing exceptions and using them to control program flow, can be a sensible way of making the logic of a program more readable and maintainable.

Problem

I have an unfortunate Java library that I've inherited that parses JSON. Right now, if you ask for a key that doesn't exist in a JSON array, it dies with a null pointer. I'm going to edit the library to do something more reasonable. I think I have two options: 1) Return null so the caller can check 2) Throw a more explicit exception (more descriptive than "Null Pointer"), forcing the caller to handle the case where they asked for a non-existent key. I come from a python background and am strongly drawn to number 2, seeing as it will ensure that some bonehead can't call this function and then continue on with a null value, crashing their application later on and possibly corrupting data. Which way do YOU think is more in line with best practices of Java? This is not a duplicate of other language-independent questions on the same topic. This is specifically in the context of Java!!!!

Original source

Related problems