Python
Python
Published on June, 6th 2025 Time To Read: 3 mins
Start your JEE ADVANCED journey now!
Python
1.7
finally Clause in Python
Exception Handling
🔹 What is the finally Clause?
-
The
finallyclause is an optional part of atrystatement in Python. -
The code inside the
finallyblock always executes, regardless of whether:-
an exception was raised, or
-
the program executed normally without errors.
-
-
It is especially useful for clean-up activities, such as:
-
Closing file streams
-
Releasing resources
-
Terminating database connections
-
-
Placement:
Thefinallyblock should always appear:-
After all
exceptblocks -
After the optional
elseblock
-
🔹 Syntax of try…except…else…finally
try:
# Code that may raise an exception
except ExceptionType1:
# Handler for ExceptionType1
except ExceptionType2:
# Handler for ExceptionType2
else:
# Executes only if no exception occurred
finally:
# Always executes, regardless of
exceptions
🔹 Example: 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")
Explanation:
-
If an exception occurs, the relevant
exceptblock handles it. -
If no exception occurs, the
elseblock executes. -
Regardless of what happens, the message “OVER AND OUT” will be printed due to the
finallyclause.
1.7.1 Recovering and Continuing with finally Clause
🔹 Behavior When Exception is Not Handled
-
If an exception occurs and is not handled by any
exceptclause:-
The
finallyblock is still executed first. -
Then the exception is re-raised, and Python searches for a higher-level handler.
-
-
This allows for guaranteed execution of clean-up code, even in unhandled exception cases.
🔹 Example: Program 1-7 — Recovering
Through finally
print("Practicing
for try block")
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")
else:
print("The
result of division operation is", quotient)
finally:
print("OVER
AND OUT")
Case 1: Input is 0
-
ZeroDivisionErroris handled. -
finallyblock executes.
Case 2: Input is a non-integer (e.g., "abc")
-
A
ValueErroroccurs (not handled here). -
Still, "OVER AND OUT" is printed from the
finallyblock. -
Then the unhandled
ValueErroris re-raised and terminates the program or passes to the outer scope.
🔹 Key Point: Flow of Control After finally
-
Once the
finallyblock completes:-
If no exception occurred → normal continuation
-
If exception was handled → program resumes normally
-
If exception was not handled → it is re-raised
-
✅ Summary of Exception Handling Flow in Python
🔸 General Structure:
-
try: Block of code where an error may occur. -
except: Handles the error if raised. -
else: Executes when no exception occurs intry. -
finally: Always executes regardless of exception.
🔸 Important Concepts:
-
Syntax Errors:
-
Detected before execution.
-
Must be corrected before running the program.
-
-
Exceptions:
-
Detected during execution.
-
Represent unexpected events or errors.
-
-
Common Built-in Exceptions:
-
SyntaxError,ValueError,IOError,KeyboardInterrupt,ImportError,EOFError,ZeroDivisionError,IndexError,NameError,IndentationError,TypeError,OverflowError
-
-
Exception Handling Workflow:
-
Python raises (throws) an exception when an error occurs.
-
Control transfers to the corresponding exception handler (
exceptblock). -
If no matching handler is found, the program terminates unless the exception is caught at a higher level.
-
The
finallyblock executes in all cases — used for cleanup and final steps.
-
-
Manual Exception Raising:
-
Use
raiseandassertto trigger exceptions deliberately.
-
-
Catch and Continue:
-
Catch exceptions using
try-exceptblocks to prevent abrupt termination and allow graceful recovery.
-
print("Practicing for try block")
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")
else:
print("The result of division operation is", quotient)
finally:
print("OVER AND OUT")
Try EaseToLearn for free
Sign up for free Online Test
Study Smarter, Not Harder - Crack JEE ADVANCED 2025
Discover expert tips, time-saving techniques, and smart strategies to boost your preparation.
Free JEE ADVANCED Mock Test
Evaluate your preparation with real undefined-level questions.