Skip to content

Computer Science · Ch 1 — Exception Handling in Python

Finally Clause

1.7

Finally Clause

The try statement can also have an optional finally clause. Statements written inside the finally block always get executed, regardless of whether an exception occurred in the try block or not, and regardless of whether it was handled by an except clause. This is why finally is commonly used when working with files or other external resources, to guarantee that the file object is closed no matter what happens during processing.

If a finally clause is used, it must be the last clause of the try statement — after every except block and after the optional else clause.

Program 1-6: Use of finally clause

print ("Handling exception using try...except...else...finally")
try:
    numerator=50
    denom=int(input("Enter the denominator: "))
    quotient=(numerator/denom)
    print ("Division performed successfully")
except ZeroDivisionError:
    print ("Denominator as ZERO is not allowed")
except ValueError:
    print ("Only INTEGERS should be entered")
else:
    print ("The result of division operation is ", quotient)
finally:
    print ("OVER AND OUT")

Consider what happens for each kind of input:

  • No exception — a valid, non-zero denominator is entered. The try block completes, else runs and prints the result, and then finally runs and prints "OVER AND OUT".
  • ZeroDivisionError — 0 is entered as the denominator. The matching except ZeroDivisionError block runs and prints its message, else is skipped, and finally still runs and prints "OVER AND OUT".
  • ValueError — a non-numeric value is entered, so int() cannot convert it. The matching except ValueError block runs and prints its message, else is skipped, and finally still runs and prints "OVER AND OUT".

In every one of these cases, the message "OVER AND OUT" will be displayed — irrespective of whether an exception is raised or not.

Note

Key points to remember about finally

  • The finally clause is optional.
  • If included, it must be the last clause of the try statement. …