Is this more of a Java tonic for exception or null return?

I have a failed Java library that I inherited that parses JSON. Right now, if you request a key that does not exist in the JSON array, it is dying with a null pointer. I am going to edit the library to make something more reasonable. I think I have two options:

1) Return zero so the caller can check

2) Throw a more explicit exception (more descriptive than the "Null Pointer"), causing the caller to handle the case when they requested a nonexistent key.

I come from a python background and are strongly attached to number 2, seeing that this will ensure that some collar cannot call this function, and then continue with a zero value, knocking down its application later and possibly corrupting the data. What do you think is more in line with Java best practices ? This is not a duplicate of other language-independent questions on the same topic. This is specifically in the context of Java !!!!

+4
source share
5 answers

This is an esoteric question!

Traditional wisdom is: -

Do not use exceptions for control flow. Exceptions should be thrown if something exceptional happens.

, NULL . (1)

Java.

, Java , , .

+3

.

null,

- "can". . , .

,

"must". , , .

,

, . , , , , , ( ) .

+7

. . , , , (ergo ).

+1

, , , , .

nulls, Null Objects, , , , - null .

0

, ( , ), , . , " "... .

Returning null is a bad practice - I think because it just leads to the fact that users of the method / class have to deal with zero, which can be forgotten and just spreads the null pointer up. Some will say that this is the right thing, however.

Another option in some cases is to return an empty object, avoiding NullPointerExceptionand not completely classifying it as an exceptional situation, but I'm not sure if this applies here.

0
source

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


All Articles