Why no try-except-finally ?

KefX keflimarcusx at aol.comNOSPAM
Wed Nov 5 04:05:56 EST 2003


This may have been discussed before, but I'm kind of confused as to why Python
doesn't support having both an except ~and~ a finally clause, like this:

try:
    raise RuntimeException
except:
    print "What is the answer?"
finally:
    print 42

This doesn't work because I use both 'except' and 'finally'. I'm not saying
that it SHOULD work, I'm wondering why it doesn't. I thought about it for a
second, though, and came up with the ad-hoc "nested-try idiom", as I call it:

try:
    try:
        raise RuntimeException
    except:
        print "What is the answer?"
finally:
    print 42

This works as expected: the exception gets thrown, the question gets asked in
the 'except' clause, and then the question gets answered in the 'finally'
clause. Of course in real-world code we wouldn't be asking questions and giving
answers via exception-handling, but the path of execution is what counts. Is
this idiom unPythonic somehow? (The nested-try thing does look odd...) Or is it
the way we're supposed to do it? Or is there something I'm missing?

- Kef





More information about the Python-list mailing list