Modify an exception before re-raising it

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Mar 6 02:18:42 EST 2009


En Fri, 06 Mar 2009 04:29:16 -0200, Steven D'Aprano <steve at pearwood.info>  
escribió:

> 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
>
> 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?

I don't completely understand your question. Is it about the bare raise?  
It is documented here:
http://docs.python.org/reference/simple_stmts.html#the-raise-statement

"If no expressions are present, raise re-raises the last exception that  
was active in the current scope. [...] The three-expression form of raise  
is useful to re-raise an exception transparently in an except clause, but  
raise with no expressions should be preferred if the exception to be  
re-raised was the most recently active exception in the current scope."

Or are you worried about modifying e.args? Hmm, it isn't explicitely  
forbidden, so I assume it's allowed... I've done it a few times -usually  
to provide more context to error messages- without bad consequences AFAICT.

-- 
Gabriel Genellina




More information about the Python-list mailing list