Exception as the primary error handling mechanism?
Lie Ryan
lie.1296 at gmail.com
Tue Jan 5 02:02:37 EST 2010
On 1/5/2010 1:31 PM, r0g wrote:
> 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
Except that that is a reinvention of try-wheel:
def foo(x):
if x > 0:
return x*x
else:
raise MathError("Bad value of x in foo: %s" % x)
try:
print foo(-1)
except MathError, e:
print "ERROR: System integrity is doubted"
or rather; that is perhaps a good example of when to use 'assert'. If
the domain of foo() is positive integers, calling -1 on foo is a bug in
the caller, not foo().
I have been looking at Haskell recently and the way the pure functional
language handled exceptions and I/O gives me a new distinct "insight"
that exceptions can be thought of as a special return value that is
implicitly wrapped and unwrapped up the call stack until it is
explicitly handled.
More information about the Python-list
mailing list