Computer Science · Ch 1 — Exception Handling in Python
Finally Clause
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
tryblock completes,elseruns and prints the result, and thenfinallyruns and prints"OVER AND OUT". ZeroDivisionError—0is entered as the denominator. The matchingexcept ZeroDivisionErrorblock runs and prints its message,elseis skipped, andfinallystill runs and prints"OVER AND OUT".ValueError— a non-numeric value is entered, soint()cannot convert it. The matchingexcept ValueErrorblock runs and prints its message,elseis skipped, andfinallystill 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.
Key points to remember about finally
- The
finallyclause is optional. - If included, it must be the last clause of the
trystatement. …