Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 770
ErlVolton Avatar asked Dec 19 '22 13:12

ErlVolton


1 Answers

It depends.

Return null so the caller can check

The keyword here is "can". The caller can completely ignore the null value. If this is completely fine, then returning null is fine.

Throw an exception so the caller must check

The keyword is "must". This is the option to take if you think the caller needs to handle the situation.

Throw an unchecked exception so the caller can check

If you do this, then you must have done it very deliberately. Basically, this lets the caller know exactly what went wrong if it does go wrong, but you don't necessarily think they need to (or will even be able to) handle the problem.

like image 166
Rainbolt Avatar answered Dec 24 '22 01:12

Rainbolt