[Python-Dev] exception chaining

Steven D'Aprano steve at pearwood.info
Sat Jan 21 01:40:15 CET 2012

Benjamin Peterson wrote:
> 2012/1/20 Terry Reedy <tjreedy at udel.edu>:
>> Since 'raise' means 're-raise the current error', 'raise as OtherError'
>> means (clearly to me, anyway) 're-raise the current error as OtherError'.
> That doesn't make any sense. You're changing the exception completely
> not reraising it.

I expect Terry is referring to the coder's intention, not the actual nuts and 
bolts of how it is implemented.

def spam():
     except HamError:
         raise SpamError

is implemented by catching a HamError and raising a completely different 
SpamError, but the intention is to "replace the HamError which actually 
occurred with a more appropriate SpamError".

At least that is *my* intention when I write code like the above, and it 
appears to be the usual intention in code I've seen that uses that idiom. 
Typically SpamError is part of the function's API while HamError is not.

The fact that Python doesn't actually "replace" anything is besides the point. 
The purpose of the idiom is to turn one exception into another exception, 
which is as close as we can get to re-raising HamError as a SpamError instead.

(It's not actually a re-raise as the traceback will point to a different line 
of code, but it's close enough.)

I'd prefer "raise SpamError from None", but I understand that this cannot work 
due to technical limitations. If that is the case, then "raise as SpamError" 
works for me.


More information about the Python-Dev mailing list