On 2/26/07, Damien Cassou damien.cassou@gmail.com wrote:
if a method should compute and return a value. If this method detects an error in its process what is the best way to indicate it:
- returning nil instead of the computed value
- raise a specific error
By my philosophy, it depends upon the expected mindset of the caller. If the programmer who uses that method expects it to sometimes fail, the programmer expects to have to check the return value for suitability. But when a method nearly always succeeds, and a programmer might not want to have to deal with the rare failure, it's probably better to raise an error.
As an example, nearly every programming language handles "divide by zero" as an error (instead of returning nil or another unsuitable object). There are a few that return a NaN instead. Mostly, when a programmer codes a division operation, the programmer isn't expecting it to fail, so it's more natural to raise an error to catch that odd case.
But consider also how those same languages handle the problem of "item not found", whether it's not finding a substring in a larger string, an object in a collection, or a web resource. Nearly always, the programmer expects to check for the possibility that the item wasn't found, and so it's natural in those cases to return nil (or whatever) to say so. Only a few raise an exception when something isn't found. Smalltalk's common way of having an #...ifNotFound: block is another kind of exception handling.
That's not to say that this is a hard-and-fast rule. On the contrary, it's a matter of judgment, and there are many cases in which reasonable people may disagree. Fortunately, in a system like Squeak, it's easy to provide both methods that raise exceptions and ones that quietly return nil at the same time. That works for programmers of either mindset.
Hope this helps!
--Tom Phoenix