Re-raising exceptions with modified message

Christoph Zwerschke cito at online.de
Sun Jul 15 05:55:13 EDT 2007


Christoph Zwerschke wrote:
> Here is a simple solution, but it depends on the existence of the args 
> attribute that "will eventually be deprecated" according to the docs:

Just found another amazingly simple solution that does neither use teh 
.args (docs: "will eventually be deprecated") attribute nor the dir() 
function (docs: "its detailed behavior may change across releases"). 
Instead it relies on the fact that the exception itselfs behaves like 
its args tuple (checked with Py 2.3, 2.4 and 2.5).

As another twist, I set the wrapper exception module to the module of 
the original exception so that the output looks more like the output of 
the original exception (i.e. simply "UnicodeDecodeError" instead of 
"__main__.UnicodeDecodeError").

The code now looks like this:

def PoliteException(e):
     E = e.__class__
     class PoliteException(E):
         def __str__(self):
             return str(e) + ", sorry!"
     PoliteException.__name__ = E.__name__
     PoliteException.__module__ = E.__module__
     return PoliteException(*e)

try:
     unicode('\xe4')
except Exception, e:
     p = PoliteException(e)
     assert p.reason == e.reason
     raise p



More information about the Python-list mailing list