Complete Exception Handling and The
finally
Clause
A common use case is to have some final processing that must occur
irrespective of any exceptions that may arise. The situation usually
arises when an external resource has been acquired and must be released.
For example, a file must be closed, irrespective of any errors that
occur while attempting to read it.
With some care, we can be sure that all exception clauses do the
correct final processing. However, this may lead to a some redundant
programming. The
finally
clause saves us the effort
of trying to carefully repeat the same statement(s) in a number of
except
clauses. This final step will be performed
before the try block is finished, either normally or by any
exception.
The complete form of a
try
statement looks like
this:
except
exception
〈,
target
〉 :
suite
Each
suite
is an indented block of
statements. Any statement is allowed in the suite. While this means that
you can have nested
try
statements, that is rarely
necessary, since you can have an unlimited number of
except
clauses.
The
finally
clause is always executed. This
includes all three possible cases: if the try block finishes with no
exceptions; if an exception is raised and handled; and if an exception
is raised but not handled. This last case means that every nested try
statement with a
finally
clause will have that
finally
clause executed.
Use a
finally
clause to close files, release
locks, close database connections, write final log messages, and other
kinds of final operations. In the following example, we use the
finally
clause to write a final log message.
def avgReport( someList ):
try:
print "Start avgReport"
m= avg(someList)
print "Average+15%=", m*1.15
except TypeError, ex:
print "TypeError: ", ex
except ZeroDivisionError, ex:
print "ZeroDivisionError: ", ex
finally:
print "Finish avgReport"