HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
returnshouldthrowproducevaluethemethodexceptionwhencan

Problem

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:

  • return null



  • throw an exception



  • other



Which is the best practise or idiom?

Solution

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.

Context

Stack Overflow Q#175532, score: 534

Revisions (0)

No revisions yet.