Re: Python Exceptions

Guido.van.Rossum@cwi.nl
Thu, 19 Jan 1995 15:09:38 +0100

> >Why do python exceptions have to be strings, couldn't they be a object that
> >has a __str__ method defined returning the string wanted. If they could
> >be we could throw generic objects around that can contain other actions.
>
> An advantage of allowing a class instance to be thrown would be that
> 'except' clauses could be extended to allow matches against classes,
> using the first match for which the specified class is a base class of
> the class of the object (i.e., the C++ exception model). Something like:
>
> class A:
> def __str__(self): return 'A class'
>
> class B(A):
> def __str__(self): return 'B class'
>
> try:
> raise B()
> except A,v:
> print str(v)
>
> should print 'B class'. Thus modules could do better than simple define
> an 'error' exception; they could define an 'error' base class, and more
> specific exceptions as needed.
>
> But one of the nicest features of Python's exception handling is that it
> is pretty light weight, so it can be used freely. I would think that adding
> this kind of feature would make it more costly to use. (But if it could
> be done without hurting performance, I think it would really be nice!)

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).

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...)

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>