Exception as the primary error handling mechanism?

r0g aioe.org at technicalbloke.com
Mon Jan 4 21:31:34 EST 2010


Michi wrote:
> On Jan 4, 1:30 pm, Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:

>> In some, limited, cases you might be able to use the magic return value
>> strategy, but this invariably leads to lost programmer productivity, more
>> complex code, lowered readability and usability, and more defects,
>> because programmers will invariably neglect to test for the special value:
> 
> I disagree here, to the extent that, whether something is an error or
> not can very much depend on the circumstances in which the API is
> used. The collection case is a very typical example. Whether failing
> to locate a value in a collection is an error very much depends on
> what the collection is used for. In some cases, it's a hard error
> (because it might, for example, imply that internal program state has
> been corrupted); in other cases, not finding a value is perfectly
> normal.



A pattern I have used a few times is that of returning an explicit
success/failure code alongside whatever the function normally returns.
While subsequent programmers might not intuit the need to test for
(implicit) "magic" return values they ought to notice if they start
getting tuples back where they expected scalars...

def foo(x)
    if x>0:
        return True, x*x
    else:
	return False, "Bad value of x in foo:",str(x)

ok, value = foo(-1)
if ok:
    print "foo of x is", value
else:
    print "ERROR:", value


Roger.



More information about the Python-list mailing list