Does Python do try: except: finally: ?

Skip Montanaro skip at pobox.com
Wed Mar 19 17:19:36 EST 2003


    >> Does Python do a block like:
    >> 
    >> try:
    >>   do_something()
    >> except:
    >>   do_something_else()
    >> finally:
    >>   do_cleanup()
    >> 

    >>> try:
    ...     print "Foo"
    ... except:
    ...     print "Oof"
    ... else:
    ...     print "Bar"
    ...
    Foo
    Bar
    >>> 

    Joseph> That what you need?

Maybe, but that's not what try/finally does.  Try/finally says, "Execute the
code in the try block, and irregardless of any exceptions which might get
raised, execute the code in the finally block when finished."
Try/except/else says, "Execute the code in the try block.  If an exception
is raised, execute the code in the except block, otherwise execute the code
in the else block."

It's tempting to think of try/except and try/finally as more closely related
than they really are.  What they have most in common is the "try" keyword.

Skip






More information about the Python-list mailing list