Exceptions as New Style Classes

Steven Taschuk staschuk at telusplanet.net
Wed Jul 30 23:14:38 CEST 2003

Quoth Andrew:
> To satisfy my curiosity I was wondering if anyone knew if this
> behaviour was intentional?
> Is there a specific reason why exceptions are not allowed to be new
> style classes?

It is intentional.

There are two difficulties with allowing new-style classes as
exception types.  Ideas exist for dealing with them, but at the
moment none of them as been implemented.

Problem 1: Implicit instantiation.  When the interpreter sees
    raise x
it must determine whether x is a class or an instance, so it can
determine whether to instantiate it.  (E.g., in
    x = TypeError
    raise x
instantiation will occur during the raise statement, whereas in
    x = TypeError()
    raise x
it will not.)  The problem is that, with new-style classes, there
is no clear and strong distinction between classes and instances,
so it is not clear how the interpreter can make this decision.

Problem 2: It is probably not desirable to allow things like
    raise 3
    raise {'d': 17}
since raising such objects as ints and dicts (etc.) is very
unlikely to be anything but a bug in practice.  (There are cases
in which you might want to do such things, but they are rare.)
However, there is (or will and should be) no clear and strong
distinction between, say, user-defined new-style classes and
built-in types, so it is not clear how the interpreter would
detect such cases and forbid them.

At the moment the dominant idea for solving these problems is to
make inheritance from Exception mandatory for exception types; see
Guido's 11 June post
for details.  (I have another idea involving a new special method
'__raise__', but haven't worked out the details yet.)

Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1

More information about the Python-list mailing list