If the API throws NullPointerExceptions

I use a commercial API and have a NullpointException coming from the API code.

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

Is this really my mistake because I did not check the parameters before passing them to the API?

Isn't it a bad practice to let NullpointerExceptions exit your API? If not, I will need to check all types of RuntimeExceptions if I use the method of this API, if I want to make sure my software will not work.

If this is bad practice, are there any documents or specifications that apply to this?

+4
source share
3 answers

Is this really my mistake because I did not check the parameters before passing them to the API?

Yes. The API defines a contract on how to use it correctly. If a value is required and not passed, I would fully expect a RuntimeException return. Before attempting to use the API, you should check your data to make sure that you are giving it what it requires. You should not catch a RuntimeException, as stonedsquirrel said.

+2
source

Yes, I would say that they should throw an IllegalArgumentException

See: IllegalArgumentException or NullPointerException for a null parameter?

And keep reading because this is the best answer: fooobar.com/questions/15397 / ...

The main difference: IllegalArgumentException makes it clear that you made a mistake when using the library.

In any case, you just need to use the library correctly. And just catch the exceptions if you can handle them.

+5
source

You say that you will need to check all the RuntimeExceptions . The answer to this question is no! It is normal for the API to throw unchecked exceptions at runtime (whether it is NullPointerException , IllegalArgumentException or something else) in case it is used incorrectly.

In your case, you are using the API incorrectly, so you get a NullPointerException . If you want to understand this, what would your code look like?

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

Why not do it just useAPIcorrectly(); ?; -)

You can add some debugging result to the catch block for development, but again: if in development, the NullPointerException stack trace is also sufficient for debugging. Then you will fix it to use the API correctly and you will never see these exceptions :-)

+4
source

Source: https://habr.com/ru/post/1502773/


All Articles