How to use the try-finally clause to handle exception in Python?



So far the try statement had always been paired with except clauses. But there is another way to use it as well. The try statement can be followed by a finally clause. Finally clauses are called clean-up or termination clauses, because they must be executed under all circumstances, i.e. a "finally" clause is always executed regardless if an exception occurred in a try block or not.

One very important point is that we can either define an “except” or a “finally” clause with every try block. You can’t club these together. Also, you shouldn’t use the “else” clause along with a “finally” clause.

Example

Given code can be rewritten as follows

try:
foo = open ( 'test.txt', 'w' )
foo.write ( "It's a test file to verify try-finally in exception handling!!")            
print 'try block executed'
finally:
foo.close ()
print 'finally block executed'

Output

try block executed
finally block executed


Advertisements