change an exception's message and re-raise it
cs at zip.com.au
Thu Dec 31 22:59:38 CET 2009
On 31Dec2009 12:18, Phlip <phlip2005 at gmail.com> wrote:
| I need to do this:
| except e:
| e.message = 'the deep arcane layer says: ' + e.message
| raise e
| The point is I need to augment that layer's exceptions with extra
| information that I know about that layer.
Doesn't the above work (modulo changing the right exception attributes)?
I've got a context manager that does something like this.
It is hampered by the fact that not all exceptions have the same
internal structure, for historic reasons I believe.
So I've got this ugly stuff in the __exit__ method:
if exc_value is not None:
if hasattr(exc_value, 'args') and len(exc_value.args) > 0:
exc_value.args = [pfx + ": " + str(exc_value.args)] \
# we can't modify this - at least report the current prefix
sys.stderr.write("%s: Pfx.__exit__: exc_value = %s\n" % (pfx,
You can see I modify the .args value.
The method returns False to let the exception percolate back out
The "else" part is to handle exceptions I can't change, so for now I've
just printing the "pfx" context on stderr as the exception bubbles out.
The calling code looks like this:
with Pfx("some tag"):
... suite ...
Cameron Simpson <cs at zip.com.au> DoD#743
There is this special biologist word we use for 'stable'. It is 'dead'.
- Jack Cohen
More information about the Python-list