[Python-Dev] Chained Exceptions
Delaney, Timothy C (Timothy)
tdelaney at avaya.com
Fri May 13 04:17:55 CEST 2005
James Y Knight wrote:
> Of course you can already do similar with current python, it just
> can't be spelled as nicely, and the default traceback printer won't
> use the info:
>
> try:
> raise AError
> except:
> newException = BError()
> newException.cause=sys.exc_info()
> raise newException
Well, one thing you can do is (somewhat evil ;)
::
import sys
try:
raise AError, 'message'
except:
exc_type, exc_value, exc_traceback - sys.exc_info()
raise BError, exc_value, exc_traceback
with the result:
Traceback (most recent call last):
File ...
raise AError, 'message'
BError: message
So you store the original exception as the argument to the new exception
(so it's accessible). This has the nice side effect that message is
displayed in the traceback - but the type has changed.
Whilst in the above example, it's particularly evil, in the case where
the original exception came from a function call and you want to
translate the type it works very nicely.
Tim Delaney
More information about the Python-Dev
mailing list