[Python-Dev] Chained Exceptions

Brett C. bac at OCF.Berkeley.EDU
Fri May 13 22:52:24 CEST 2005


Guido van Rossum wrote:
> [Guido]
> 
>>>What if that method catches that exception?
> 
> 
> [Ka-Ping Yee]
> 
>>Did you mean something like this?
>>
>>    def handle():
>>        try:
>>            open('spamspamspam')
>>        except:
>>            catchit()
>>            # point A
>>            ...
>>
>>    def catchit():
>>        try:
>>            1/0
>>        except:
>>            pass
>>
>>Then there's no exception to propagate, so it doesn't matter.
>>Once we're get to point A, the division by zero is long forgotten.
> 
> 
> But at what point does the attaching happen? If I catch the
> ZeroDivisionException inside catchit() and inspects its context
> attribute, does it reference the IOError instance raised by
> open('spamspamspam')?

Yes, at least in the way I am imagining this being implemented.  I was thinking
that when an exception happens, the global exception variable is checked to see
if it has a value.  If it does that gets assigned to the new exception's
'context' attribute and the new exception gets assigned to the global exception
variable.

> This could potentially cause a lot of extra
> work: when an inner loop that raises and catches lots of exceptions is
> invoked in the context of having caught an exception at some outer
> level, the inner loop keeps attaching the outer exception to each
> exception raised.
> 

[this also contains a partial answer to Philip's email also in this thread]

Maybe, but as long as caught exceptions get cleared that should be an issue.
Would this be solved if, when an 'except' branch is exited, exceptions are
cleared?  So, in the above example, once the 'pass' is hit in catchit() no
exception is considered active any longer.  This could be done with a CLEAR_EXC
opcode very easily inserted at the end of an 'except' branch by the compiler.

This would require explicit re-raising of exceptions to keep them alive after
an 'except' ends, but I think that is actually a good idea and since this might
all wait until Python 3000 anyway we don't need to worry about the semantic change.

-Brett


More information about the Python-Dev mailing list