[Python-Dev] Exception hierarchy [was Re: Another test_compiler mystery]

James Y Knight foom at fuhm.net
Tue Aug 17 02:07:14 CEST 2004


On Aug 16, 2004, at 7:29 AM, Armin Rigo wrote:
> Yes.  Here is a patch attempting to do what I described:
>  http://www.python.org/sf/1009929


 From the patch description:
>  Some more thinking about [the exception hierarchy] would be welcome. 
> Maybe AsynchronousException and a few others should not subclass 
> Exception at all, so that "except Exception" statements don't catch 
> them. Anyway, this patch alreaddy improves the situation, because you 
> can catch and re-raise AsynchronousException (instead of, say, just 
> KeyboardInterrupt).

It seems to me that something similar to what Java has would be a good 
idea. Namely, a new top level exception (from which all others would 
derive) called "Raisable", analogous to Java's Throwable. This then has 
two subclasses: "Exception", and "FatalError". I'm not sure FatalError 
is a good name, but *some* new name needs to be thought up for Java's 
"Error" class, because lots of python exceptions end in "Error" but 
belong under the "Exception" hierarchy (for example "KeyError").

The criteria for whether a given exception should go under "Exception" 
or "FatalError" is whether users' code should generally catch the 
exception. Thus, at least "SystemExit", "KeyboardInterrupt", and 
"MemoryError" should go under "FatalError". Catching those is nearly 
never what you wanted to do when you write "except Exception:". There's 
likely more -- I have not gone through all the exceptions in Python to 
classify them.

One issue is that creating a new category of Exceptions doesn't help 
people who do "except:" instead of "except Exception:". It is unlikely 
that person meant to catch things like MemoryError, rather, they were 
just being lazy. I suppose that syntax could be deprecated, at least in 
example code and documentation, in favor of "except Exception" for the 
usual case, and "except Raisable" for the cases where you do actually 
want to catch everything*.

James

* Except, of course, old string exceptions which have been deprecated 
for ages.



More information about the Python-Dev mailing list