Re-raising exceptions with modified message

Christoph Zwerschke cito at
Thu Jul 5 21:20:13 EDT 2007

Alex Popescu wrote:
> Probably the simplest solution would be to create a new exception and
> wrapping the old one and the additional info. Unfortunately, this 
> may have a huge impact on 3rd party code that was catching the 
> original exception. So, I think you should create an utility 
> factory-like function that is either creating a new exception 
> instance as the one caught and with the additional information,

Right, I have gone with that (see the example with the PoliteException 
class somewhere below).

> or an utility that knows how to modify the caught exception according
> to its type.

I guess you mean something like this (simplified):

except Exception, e:
     if getattr(e, 'reason'):
         e.reason += "sorry"
         e.message += "sorry"

The problem is that these attribute names are not standardized and can 
change between Python versions. Not even "args" is sure, and if a class 
has "message" it does not mean that it is displayed. Therefore I think 
the first approach is better.

> In the first case you will need somehow to tell to the new instance
> exception the real stack trace, because by simply raising
> a new one the original stack trace may get lost.

Yes, but thats a different problem that is easy to solve.

-- Chris

More information about the Python-list mailing list