How to pop the interpreter's stack?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Dec 25 17:49:08 EST 2010
On Sat, 25 Dec 2010 09:17:27 -0500, Robert Kern wrote:
> On 12/24/10 5:14 PM, Ethan Furman wrote:
>
>> There are also times when I change the exception being raised to match
>> what python expects from that type of object -- for example, from
>> WhatEverException to KeyError for a dict-like object. So in this regard
>> I agree with Steven.
>
> Steven isn't arguing that particular point here, nor is anyone arguing
> against it.
Emphasis on *here*.
You will note that in Python 3, if you raise an exception inside an
except block, both the *original* and the new exception are printed. This
is great for fixing bugs inside except blocks, but terribly disruptive
for catching one error and raising another error in it's place, e.g.:
try:
x+0
except ValueError, TypeError as e:
# x is not a numeric value, e.g. a string or a NAN.
raise MyError('x is not a number')
The explicit raise is assumed to indicate a bug in the except block, and
the original exception is printed as well.
But that's a separate issue from what is being discussed here. What we're
discussing here is the idea that a function should be able to delegate
work to private subroutines without the caller being aware of that fact.
When you return a value, the caller doesn't see the internal details of
how you calculated the value, but if you deliberately raise an exception,
the caller does. Often this is the right thing to do, but sometimes it
isn't. E.g. you can't delegate input validation to a subroutine and raise
inside the subroutine without obfuscating the traceback.
--
Steven
More information about the Python-list
mailing list