Re-raising exceptions with modified message

samwyse samwyse at gmail.com
Sat Jul 7 23:01:53 EDT 2007


On Jul 5, 8:53 am, Christoph Zwerschke <c... at online.de> 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
http://lucumr.pocoo.org/cogitations/2007/06/16/patching-python-tracebacks-part-two/


# Written by Sam Denton <samwyse at gmail.com>
# 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):
    try:
        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