[Python-Dev] Proposal - KeyboardInterrupt should inherit directly from Exception

Skip Montanaro skip@pobox.com (Skip Montanaro)
Wed, 07 Nov 2001 10:39:42 +0100


Consider this code posted to c.l.py in the past day or two:

    try:
       x = float(s)
       result = 1
    except:
       result = 0

to which Andrew Kuchling replied:

    It's better to catch ValueError and not all exceptions.  Else
    what would happen if you get a MemoryError or a KeyboardInterrupt?

All well and good.  There are situations other than in throwaway code
where you do want a more-or-less catchall except clause (any time you
are executing arbitrary code for which you don't know all the
exceptions that might be raised), but you generally have to remember
to code it as

    try:
        fragile code
    except (SystemExit, KeyboardInterrupt):
        raise
    except:
        recover

I have a simple proposal: Change the exception class hierarchy
slightly, so that exceptions you generally will want to re-raise don't
inherit from StandardError.  Currently, SystemExit, StopIteration and
Warning inherit directly from Exception.  I suggest that
KeyboardInterrupt should also inherit from Exception, and not
StandardError.  That way, the standard catch all except clause can be

    try:
        fragile code
    except StandardError:
        recover

and use of bare except clauses can be discouraged more strongly than
they currently are.  (Maybe MemoryError should inherit directly from
Exception as well because recovery opportunities should that arise are
going to be minimal and fall into a decidely different set of options
than, say, recovering from invalid numeric input by a user.)

Pro: Programmers won't have to remember to consider SystemExit and
KeyboardInterrupt when coding catch-all excepts.

Con: Slightly changes the semantic implications of "except
StandardError".  I doubt this is used much, but I see that it is used
by test_cgi.py and xml/dom/domreg.py.  Both of those cases would have
to be recoded. (Actually, I think the domreg.py case may be an error,
since it doesn't catch and re-raise KeyboardInterrupt...)

Thoughts?

-- 
Skip Montanaro (skip@pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/