Re: Python Exceptions

R Lindsay Todd (toddr@rpi.edu)
Thu, 19 Jan 1995 13:39:06 +22295707

> Hmm... Although I see the elegance of this design (which looks
> similar to C++'s throw/catch mechanism), I don't see how it adds any
> power compared to the current approach. Note that there is already a
> mechanism whereby you can collect a number of specific exceptions into
> a tuple, name that tuple, and specify exception handlers for the tuple
> (for examples the ftplib library module uses this).

While I've played a little with exceptions in C++, it's been pretty limited,
mostly because exception support in most compilers is missing. But I got to
thinking about how you could use multiple inheritance to allow a module to
define exceptions with several orthogonal attributes.

For example, maybe Python supplies several builtin error classes, like:
OverflowError_cl, KeyError_cl, AttributeError_cl, ...

A module, say 'Record', may define a 'RecordError_cl'. It would subclass this
with other errors, maybe using multiple inheritance with AttributeError_cl, to
make a 'RecordAttributeError_cl' class. A client of this module could catch
the error either as RecordError_cl', 'AttributeError_cl', or as
'RecordAttributeError_cl', whichever made the most sense in the code...

Maybe this isn't the best example, but let your imagination go with it.

> About the only advantages of raising class instances would be that you
> don't need to peek in sys.exc_type to find out the most detailed name
> for the exception just raised. But the check for whether an exception
> clause matches the raised exception would be more complicated, as it
> would have to traverse the tree of base classes (in the case of
> multiple inheritance) to detect a match. Perhaps someone with more
> time could write the code and see how it performs? (Compatibility
> would be required, too, but that should be pretty simple -- raise
> should accept either a string or a class instance...)

It doesn't look like it would be hard to do, and the current matching against
string tuples probably isn't much less costly. I hope someone tries this...

R. Lindsay Todd, Systems Programmer, Rensselaer Polytechnic Institute, Troy NY
toddr@rpi.edu / 518-276-2605 / http://www.rpi.edu/~toddr/Home.html