Should a retrieval method return 'null' or throw an exception when it can't produce the return value? [closed]

I am using java language,I have a method that is supposed to return an object if it is found.

If it is not found, should I:

  1. return null
  2. throw an exception
  3. other

Which is the best practise or idiom?


Solution 1:

If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.

If the value can be missing or present and both are valid for the application logic then return a null.

More important: What do you do other places in the code? Consistency is important.

Solution 2:

Only throw an exception if it is truly an error. If it is expected behavior for the object to not exist, return the null.

Otherwise it is a matter of preference.

Solution 3:

As a general rule, if the method should always return an object, then go with the exception. If you anticipate the occasional null and want to handle it in a certain way, go with the null.

Whatever you do, I highly advise against the third option: Returning a string that says "WTF".