Modify an exception before re-raising it
Steve Holden
steve at holdenweb.com
Fri Mar 6 02:26:22 EST 2009
Steven D'Aprano 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?
>
>
Yes, "raise" on its own is specifically documented (he says, without
consulting the documentation - but then if you didn't, why should I?) to
re-raise a current exception. I see no reason why you shouldn't modify
your exception before the re-raise. You certainly don't want to raise
the exception explicitly, since as you have just discovered that will
alter its traceback.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Want to know? Come to PyCon - soon! http://us.pycon.org/
More information about the Python-list
mailing list