Re-raise different exception with original stack trace

Ian Kelly ian.g.kelly at gmail.com
Tue Oct 18 15:45:26 EDT 2011


On Tue, Oct 18, 2011 at 12:23 PM, Prasad, Ramit
<ramit.prasad at jpmorgan.com> wrote:
> Yes, but raising the CustomException replaces the last traceback and even with the saved exception, how would you get the original stacktrace? The only thing I can think is get the stacktrace and store it in the exception. That does not seem very Pythonic to me.

In Python 3 you could chain the exceptions with:

   except Exception as e:
       raise CustomException() from e

There is no such syntax in Python 2, but you could manually store and
retrieve the __cause__ and __traceback__ attributes similarly to the
way Python 3 does it.  See PEP 3134 for full details.

HTH,
Ian



More information about the Python-list mailing list