Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a API throw NullPointerExceptions

I use a commerical API and had a NullpointException coming from the API code.

The support tells me that it is expected because one of the input-parameters of the method I called was null and this parameter is needed to use the methdod.

Is this really my fault because I haven't checked the parameters before passing them to the API?

Isn't it bad practice to let NullpointerExceptions out of your API? If not I would have to check for all kind of RuntimeExceptions if I use a method of that API if I want to make sure my software doesn't crash.

If it is bad practice, are there any documents or specifications which refer to this?

like image 541
Felix Schmidt Avatar asked Dec 20 '22 00:12

Felix Schmidt


2 Answers

Yeah, I would say they should throw IllegalArgumentException

See: IllegalArgumentException or NullPointerException for a null parameter?

And do read on, because this is the best answer: https://stackoverflow.com/a/47710/2586804

The main difference is IllegalArgumentException makes it explicit that you have made a mistake when using the library.

Either way, you just need to use the library correctly. And only catch exceptions if you can handle them.

like image 103
user2586804 Avatar answered Jan 06 '23 10:01

user2586804


You say that you would have to check for all RuntimeExceptions. The answer to that is no! It's OK for an API to throw unchecked runtime exceptions (regardless if it's a NullPointerException, a IllegalArgumentException or something else) in case it is used the wrong way.

In your case you use the API the wrong way, so you get a NullPointerException. If you want to catch that, how would your code look like?

try {
    useAPI();
} catch(NullPointerException e) {
    useAPIcorrectly();
}

Why not make that just useAPIcorrectly();? ;-)

You could put some debuging output in the catch block for development but the again: If in development, the stack trace of a NullPointerException is also sufficient for debugging. You would then fix it to the correct API use and never see those exceptions again :-)

like image 29
André Stannek Avatar answered Jan 06 '23 11:01

André Stannek