Re: Python Exceptions

Jack Jansen (Jack.Jansen@cwi.nl)
Mon, 23 Jan 1995 22:04:14 GMT

Guido.van.Rossum@cwi.nl writes:
>>
>> 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.
>>

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

It adds a possibility that I would dearly like: catching exceptions
you don't want to know anything about. Consider a module A which uses
a module B and both define an exception 'error'. Calls to A methods
may raise either A.error or B.error. Currently, you can design stuff
in two ways:
1) In A, bracket all calls to B with
try:
B.method()
except B.error, arg:
raise error, arg
2) Import B in the main code, and use"except (A.error, B.error)"
everywhere.

(1) is lousy, since you loose information, (2) is ugly and difficult
to maintain (since implementation changes to A, like using another
module C, may result in the need to change the main code too).

I've come across this situation a few times already, most recently
with the image file stuff.

An alternative to using classes for exceptions could be to invent some
new idiom, as in
# Module A
import B
import C

_error = 'A.error'
error = (_error,) + B.error + C.error
but this will fail if people try to compare an exception to A.error.

-- 
--
Jack Jansen        | If I can't dance I don't want to be part of
Jack.Jansen@cwi.nl | your revolution             -- Emma Goldman
uunet!cwi.nl!jack    G=Jack;S=Jansen;O=cwi;PRMD=surf;ADMD=400net;C=nl