Modify an exception before re-raising it

Steven D'Aprano steve at pearwood.info
Fri Mar 6 01:29:16 EST 2009


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?


-- 
Steven




More information about the Python-list mailing list