Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have the following code

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

How do I rewrite this code to use finally clause?


1 Answer
Manogna

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.

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.