Re-raising exceptions with a different type and message, preserving existing information

Ben Finney ben+python at benfinney.id.au
Mon Mar 30 01:36:15 EDT 2009


Howdy all,

I'm writing a module and want to have a unified exception hierarchy
for the exceptions that it can raise. This allows users of the module
to catch those particular exceptions and handle them distinctly, if
needed. But many of the exceptions raised from the module are raised
because of some other exception; e.g. failing at some task because of
an OSError on a file.

What I need is to “wrap” the exception caught such that it has a
different type and message. But I don't want to lose the existing
type, message, and stack trace; that's all useful information for
someone trying to debug the problem.

Python's PEP 3134 “Exception Chaining and Embedded Tracebacks”
discusses a change accepted in Python 3.0 for “chaining” exception
objects, to indicate that a new exception was raised during the
handling of an existing exception.

What I'm trying to do is related: I need it working in earlier Python
versions, and I need it not for chaining, but only for polymorphism.
What is the right way to do this?

-- 
 \       “… whoever claims any right that he is unwilling to accord to |
  `\             his fellow-men is dishonest and infamous.” —Robert G. |
_o__)           Ingersoll, _The Liberty of Man, Woman and Child_, 1877 |
Ben Finney



More information about the Python-list mailing list