Specifying Cleanup Actions

finally

  • Used to supply code that must execute no matter what happens
     f = open(filename)
     try:
          statements
     finally:
          f.close()
  • finally is not used to catch errors. It only specifies a cleanup action.
  • Executes regardless of whether or not an exception occurs.
  • finally and except can not appear together in the same try statement.

try-else

     try:
         statements
     except IOError,e:
         statements
     else:
         statements
  • else clause only executes if no exception occurred (and it must appear last).
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 72
July 17, 2000, beazley@cs.uchicago.edu
>>>