I'm working on a mail-sending library, and I want to be able to catch exceptions produced by the senders (SMTP, Google AppEngine, etc.) and wrap them in easily catchable exceptions specific to my library (ConnectionError, MessageSendError, etc.), with the original traceback intact so it can be debugged. What is the best way to do this in Python 2?
+3
A:
The simplest way would be to reraise with the old trace object. The following example shows this:
import sys
def a():
def b():
raise AssertionError("1")
b()
try:
a()
except AssertionError: # some specific exception you want to wrap
trace = sys.exc_info()[2]
raise Exception("error description"), None, trace
Check the documentation of the raise statement for details of the three parameters. My example would print:
Traceback (most recent call last):
File "C:\...\test.py", line 9, in <module>
a()
File "C:\...\test.py", line 6, in a
b()
File "C:\...\test.py", line 5, in b
raise AssertionError("1")
Exception: error description
AndiDog
2010-10-02 21:06:31
@Thomas Wouters: And why would I want to do that? That way, I only get the exception instance but not its trace object.
AndiDog
2010-10-02 21:29:42
Durr, yes, nevermind me. I misremembered the order of things returned by `sys.exc_info()`.
Thomas Wouters
2010-10-02 21:38:36
This looks good. Thanks!
LeafStorm
2010-10-05 13:45:07