Re-raising exceptions with modified message

Neil Cerutti horpner at
Thu Jul 5 16:53:39 CEST 2007

On 2007-07-05, Christoph Zwerschke <cito at> wrote:
> Thomas Heller wrote:
>> I have the impression that you do NOT want to change the
>> exceptions, instead you want to print the traceback in a
>> customized way.  But I may be wrong...
> No, I really want to modify the exception, supplementing its
> message with additional information about the state of the
> program.
> The use case are compiled Kid templates
> ( If an error occurs, I want to add
> the corresponding line number of the XML file as information
> for the template developer. Since the final error handling may
> happen somewhere else (e.g. by TurboGears importing a Kid
> template), I do not want to modify trackeback handling or
> something.

The documentation for BaseException contains something that might
be relevant:

   [...] If more data needs to be attached to the exception,
   attach it through arbitrary attributes on the instance. All
   arguments are also stored in args as a tuple, but it will
   eventually be deprecated and thus its use is discouraged. New
   in version 2.5. [...]

I don't know if something like the following would help:

>>> def foo():
...   try:
...     12/0
...   except ZeroDivisionError, e:
...     e.my_info = "Oops!"
...     raise
>>> try:
...   foo()
... except ZeroDivisionError, e:
...   print e.my_info

Users could get at the extra info you attached, but it wouldn't
be automatically displayed by the interpreter.

Neil Cerutti
Symphonies of the Romantic era were a lot longer in length. --Music Lit Essay

More information about the Python-list mailing list