change an exception's message and re-raise it

Stephen Hansen apt.shansen at gmail.com
Thu Dec 31 15:39:52 EST 2009


On Thu, Dec 31, 2009 at 12:18 PM, Phlip <phlip2005 at gmail.com> wrote:

> The point is I need to augment that layer's exceptions with extra
> information that I know about that layer.
>
>
I would take advantage of the fact that exceptions are real, full-blown
objects, and not just treat them as something that holds a string.

Meaning:

class DeepException(Exception):
    pass

class ShallowException(DeepException): # you may or may not really want to
inherit from DeepException
   def __init__(self, deep_exception, more_information):
       self.message = more_information
       self.deep_exception = deep_exception

try:
   deep_arcane_layer()
except DeepException d:
  raise ShallowException(d, "Some other information")

Then if someone catches ShallowException, they can check out the 'message'
attribute (which could have come from the DeepException, or "Some Other
Information", and contain whatever information this higher layer knows in
however many attributes/messages). If they want to get at the original
exception, its available as an attribute, with all of the information that
it had.

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091231/d4e45918/attachment.html>


More information about the Python-list mailing list