Re: Python Exceptions

R Lindsay Todd (toddr@narnia.its.rpi.edu)
18 Jan 1995 20:03:00 GMT

Someone recently wrote:

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

/Lindsay

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