change an exception's message and re-raise it
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Dec 31 19:30:32 EST 2009
On Thu, 31 Dec 2009 12:18:42 -0800, Phlip wrote:
> Pythonistas:
>
> I need to do this:
>
> try:
> deep_arcane_layer()
> except e:
> e.message = 'the deep arcane layer says: ' + e.message
> raise e
Use e.args, not e.message. The message attribute is deprecated from
Python 2.6 and will print a warning if you try to use it.
> The point is I need to augment that layer's exceptions with extra
> information that I know about that layer.
>
> I naturally cannot use the argless version of 'raise', because it only
> re-raises whatever exception object is currently in play - and it
> appears to be read-only or locked or something.
Changing args works:
>>> try:
... 1/0
... except ZeroDivisionError, e:
... e.args = e.args + ('fe', 'fi', 'fo', 'fum')
... raise
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: ('integer division or modulo by zero', 'fe', 'fi',
'fo', 'fum')
> I also should not do this...
>
> raise Exception('blah ' + e.message)
>
> ...because that stripped off the exception type itself, and higher
> layers need to know this.
For the record you can get the exception type from type(e):
raise type(e)("whatever you want")
but that creates a new exception, not re-raising the old one.
--
Steven
More information about the Python-list
mailing list