4

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?

mfirry
  • 3,634
  • 1
  • 26
  • 36
Felix Schmidt
  • 321
  • 1
  • 3
  • 13
  • possible duplicate of [IllegalArgumentException or NullPointerException for a null parameter?](http://stackoverflow.com/questions/3881/illegalargumentexception-or-nullpointerexception-for-a-null-parameter) – Jayan Sep 18 '13 at 09:38
  • Let your software crash. Trying to carry on after all exceptions doesn't work. – artbristol Sep 18 '13 at 10:49

3 Answers3

5

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.

Community
  • 1
  • 1
user2586804
  • 321
  • 1
  • 10
4

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 :-)

André Stannek
  • 7,773
  • 31
  • 52
2

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

Yes. The API defines the contract for how it can be used correctly. If a value is required and not passed in, I would fully expect a RuntimeException to come back. You should be doing validation on your data before you try to use the API to ensure you're giving it what's required. You should not be catching RuntimeException, as stonedsquirrel said.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52