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 finally clause is an optional part of a try statement in Python.

  • The code inside the finally block 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:
    The finally block should always appear:

    • After all except blocks

    • After the optional else block


🔹 Syntax of try…except…else…finally

python
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

python
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 except block handles it.

  • If no exception occurs, the else block executes.

  • Regardless of what happens, the message “OVER AND OUT” will be printed due to the finally clause.


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 except clause:

    • The finally block 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

python
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

  • ZeroDivisionError is handled.

  • finally block executes.

Case 2: Input is a non-integer (e.g., "abc")

  • A ValueError occurs (not handled here).

  • Still, "OVER AND OUT" is printed from the finally block.

  • Then the unhandled ValueError is re-raised and terminates the program or passes to the outer scope.


🔹 Key Point: Flow of Control After finally

  • Once the finally block 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 in try.

  • 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:

    1. Python raises (throws) an exception when an error occurs.

    2. Control transfers to the corresponding exception handler (except block).

    3. If no matching handler is found, the program terminates unless the exception is caught at a higher level.

    4. The finally block executes in all cases — used for cleanup and final steps.

  • Manual Exception Raising:

    • Use raise and assert to trigger exceptions deliberately.

  • Catch and Continue:

    • Catch exceptions using try-except blocks 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")

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.

Start Now

Free JEE ADVANCED Mock Test

Start Now