[Python-Dev] Chained Exceptions

Ka-Ping Yee python-dev at zesty.ca
Fri May 13 00:32:50 CEST 2005


Suppose exceptions have an optional "context" attribute, which is
set when the exception is raised in the context of handling another
exception.  Thus:

    def a():
        try:
            raise AError
        except:
            raise BError

yields an exception which is an instance of BError.  This instance
would have as its "context" attribute an instance of AError.

Or, in a more complex case:

    def compute():
        try:
            1/0
        except Exception, exc:
            log(exc)

    def log(exc):
        try:
            file = open('error.log')   # oops, forgot 'w'
            print >>file, exc
            file.close()
        except:
            display(exc)

    def display(exc):
        print 'Aaaack!', ex            # oops, misspelled 'exc'

Today, this just gives you a NameError about 'ex'.

With the suggested change, you would still get a NameError about 'ex';
its 'context' attribute would show that it occurred while handling an
IOError on error.log; and this IOError would have a 'context' attribute
containing the original ZeroDivisionError that started it all.

What do you think?


-- ?!ng


More information about the Python-Dev mailing list