saving an exception

Ben Cartwright bencvt at
Tue Oct 3 08:18:42 CEST 2006

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
    except Exception:
        # Build a new exception of the same type with the inner stack
        exctype = sys.exc_info()[0]
        exception = exctype('\nInner ' +

if exception:
    raise exception

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


More information about the Python-list mailing list