Wrapping exceptions in Python

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

For completeness, in Python 3 you’d use the raise MyException(...) from e syntax.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)