468,287 Members | 1,999 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,287 developers. It's quick & easy.

saving an exception

hi,

i would like to save an exception and reraise it at a later time.
something similar to this:

exception = None
def foo():
* * try:
* * * * 1/0
* * except Exception, e:
* * * * exception = e

if exception: raise exception
i have a need to do this because in my example foo is a callback from c code
which was originally called from python and i can't modify the c code.
with the above code, i'm able to successfully raise the exception, but the
line number of the exception is at the place of the explicit raise instead
of the where the exception originally occurred. *is there anyway to fix
this?
thanks,

bryan

Oct 3 '06 #1
1 1133
Bryan wrote:
i would like to save an exception and reraise it at a later time.

something similar to this:

exception = None
def foo():
try:
1/0
except Exception, e:
exception = e

if exception: raise exception

with the above code, i'm able to successfully raise the exception, but the
line number of the exception is at the place of the explicit raise instead
of the where the exception originally occurred. is there anyway to fix
this?
Sure: generate the stack trace when the real exception occurs. Check
out sys.exc_info() and the traceback module.

import sys
import traceback

exception = None
def foo():
global exception
try:
1/0
except Exception:
# Build a new exception of the same type with the inner stack
trace
exctype = sys.exc_info()[0]
exception = exctype('\nInner ' +
traceback.format_exc().strip())

foo()
if exception:
raise exception

# Output:
Traceback (most recent call last):
File "foo.py", line 15, in <module>
raise exception
ZeroDivisionError:
Inner Traceback (most recent call last):
File "foo.py", line 8, in foo
1/0
ZeroDivisionError: integer division or modulo by zero

--Ben

Oct 3 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by kaosyeti | last post: by
5 posts views Thread by Thaynann | last post: by
1 post views Thread by M Keeton | last post: by
reply views Thread by NPC403 | last post: by
2 posts views Thread by MrBee | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.