Complete Exception Handling and The
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
clause saves us the effort
of trying to carefully repeat the same statement(s) in a number of
clauses. This final step will be performed
before the try block is finished, either normally or by any
The complete form of a
statement looks like
is an indented block of
statements. Any statement is allowed in the suite. While this means that
you can have nested
statements, that is rarely
necessary, since you can have an unlimited number of
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
clause will have that
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
clause to write a final log message.
def avgReport( someList ):
print "Start avgReport"
print "Average+15%=", m*1.15
except TypeError, ex:
print "TypeError: ", ex
except ZeroDivisionError, ex:
print "ZeroDivisionError: ", ex
print "Finish avgReport"