Python gets right what Java already has, and .NET still hasn't

In the Java world, you have the base type of java.lang.Throwable, and the subclasses of java.lang.Error (you basically never catch this, at least not in application code) and java.lang.Exception (this you can use to your heart’s content).

In .NET, for various reasons (and yes, I’ve had threads internally about this, including with Chris), there’s no such split of the hierarchy.  There’s the base type System.Exception.  There’s also a subclass called ApplicationException, where the idea was that we’d do our exception split there with a SystemException and ApplicationException split.  However, even we couldn’t keep that straight, so now even we consider it useless.

Why bother bringing this all up now?

Because it looks like Python 3.0 is going to get it right.  They’re doing what I think .NET should do at this point – give Exception a new superclass.  Is it trivial?  No.  Will it break existing source?  Yes.  Is it the right long-term answer?  I think so.

In addition to the deprecation of raising strings as exceptions, Python 2.5 also rearranged the exception class hierarchy. The new BaseException class is the base class for Exception. You should now derive all your custom exception classes from Exception, or from a class derived from Exception.

Two other exception classes, KeyboardInterrupt and SystemExit, also extend BaseException, but not Exception. Thus, you can trap your own exceptions, and then trap all other exceptions derived from Exception. This will trap every exception except KeyboardInterrupt and SystemExit. Why would you not want to trap those two exceptions? That way your program will end when the user presses Ctrl+C without you having to manually catch and respond to Ctrl+C, or without you having to manually skip catching Ctrl+C to let the system handle it. The same is true with the SystemExit exception, which should force the program to stop.

This particular new feature, then, is less of a feature and more of a requirement: Recode your exception classes to extend Exception. Then you’ll be fine when Python 3.0 arrives.


One thought on “Python gets right what Java already has, and .NET still hasn't

  1. I think they should use monads instead ;). type Maybe = Nothing | Some

    On a side note, .Net exceptions don’t include SystemExit nor KeyboardInterrupt, so they aren’t caught by catching Exception, which leaves less of the problem that you describe with Python < 3.

Comments are closed.