[Tutor] finally

Steven D'Aprano steve at pearwood.info
Fri Jun 25 02:41:07 CEST 2010

On Thu, 24 Jun 2010 11:06:24 pm Hugo Arts wrote:
> If you need to do some cleanup, putting it in a finally block is the
> only way to *guarantee* it will run.

To be pedantic, the finally clause will always run, *provided* the code 
in the try block itself exits (either by finishing or by raising an 
exception). If the try block never exits, the finally block never runs.

# Don't try this at home.
    print "Can't stop this!"
    while 1:
    print "This never prints"

The only way to exit the loop is to hit it with a hammer (kill it from 
outside Python), in which case the finally block never gets to run.

Steven D'Aprano

More information about the Tutor mailing list