Re-raising exceptions with modified message

samwyse samwyse at
Sun Jul 8 05:01:53 CEST 2007

On Jul 5, 8:53 am, Christoph Zwerschke <c... at> wrote:
> What is the best way to re-raise any exception with a message
> supplemented with additional information (e.g. line number in a
> template)? Let's say for simplicity I just want to add "sorry" to every
> exception message.

OK, this seems pretty minimal, yet versatile.   It would be nice to be
able to patch the traceback, but it turns out that it's fairly hard to
do. If you really want to do that, however, go take a look at

# Written by Sam Denton <samwyse at>
# You may use, copy, or distribute this work,
# as long as you give credit to the original author.
def rewriten_exception(old, f):
    class Empty(): pass
    new = Empty()
    new.__class__ = old.__class__
    new.__dict__ = old.__dict__.copy()
    new.__str__ = f
    return new

def test(code):
    except Exception, e:
        raise rewriten_exception(e, lambda: str(e) + ", sorry!")

test(lambda: unicode('\xe4'))
test(lambda: 1/0)

More information about the Python-list mailing list