Modify an exception before re-raising it

Chris Rebert clp2 at rebertia.com
Fri Mar 6 07:49:47 CET 2009


On Thu, Mar 5, 2009 at 10:29 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> I wish to catch an exception, modify the error message, and re-raise it.
> There are two ways I know of to do this, with subtly different effects:
>
>>>> def raise_example1():
> ...     try:
> ...             None()
> ...     except TypeError, e:
> ...             e.args = ('modified error message',) + e.args[1:]
> ...             raise e
> ...
>>>> def raise_example2():
> ...     try:
> ...             None()
> ...     except TypeError, e:
> ...             e.args = ('modified error message',) + e.args[1:]
> ...             raise
> ...
>>>> raise_example1()
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>  File "<stdin>", line 6, in raise_example1
> TypeError: modified error message
>>>> raise_example2()
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
>  File "<stdin>", line 3, in raise_example2
> TypeError: modified error message
>
> Note how the line numbers in the traceback are different.
>
> The behaviour I want is from raise_example2, but I'm not sure if this is
> documented behaviour, or if it is something I can rely on. Is it acceptable
> to modify an exception before re-raising it?

Doesn't really answer the question you asked, but if you're using
Python 3.0, you might want to consider using the new `raise
AnException from AnotherException` feature rather than changing the
error message. See
http://docs.python.org/3.0/reference/simple_stmts.html#raise for
details.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-list mailing list