Try block problem

Skip Montanaro skip at
Tue Nov 20 12:37:41 CET 2001

    Jeff>         It seems like the following makes sense to me:
    Jeff> try:
    Jeff>         ...
    Jeff> except:
    Jeff>         ...
    Jeff> finally:
    Jeff>         ...

    Jeff> I know it doesn't work, my question is: why? 

They are solving two different language problems, so it also makes some
sense to keep them separate.  Typically, try/finally is used to perform some
local cleanup before a function exits.  I've never seen it used to perform
cleanup of data from deeper frames of execution.  Try/except, on the other
hand, is frequently used to recover from problems detected in (possibly
deeply) nested frames of execution.  If you really need both, you can be

        except OverflowError:
            print "hey dummy! looks like you might have divided by zero!"
        print "thank god that block is done! that was rough!"

The thing that is perhaps slightly misleading is the use of the "try"
keyword to begin both constructs.  There's really no "try" connotation to
try/finally.  It has more the semantics "do this/then clean up before you
leave", but those would be rather cumbersome keywords to type.  I also
suspect the two uses of "try" were added at different times.  Perhaps that's
not the case for the Ruby construct you mentioned.

    Jeff> Is it difficult to implement in python? 

I suspect it wouldn't be trivial, but I don't know.  That it took heroic
efforts to allow continue statements within try blocks (new with 2.1 or 2.2
I think) suggests that getting too elaborate with what you allow would be
fairly hard to implement.  On the other hand, I don't believe Guido views it
as an implementation deficiency the way "continue within try" was.

    Jeff> ... which brings another question: does every language make new
    Jeff> keywords for the same concept of exceptions, or are they different
    Jeff> somehow?

So it would seem.  I'm sure there's a bit of NIH going on.  ;-)

Skip Montanaro (skip at -

More information about the Python-list mailing list