Nearby lessons

83 of 159

Python - Finally Block

📌 What You Will Learn
  • Understand why clean-up code should live in a finally block instead of try or except
  • Know that finally executes whether an exception is raised, handled, or neither
  • Trace the execution order of try, except, else, and finally in every case
  • Learn the one situation where the finally block is skipped - os._exit(0)

Why Do We Need the finally Block?

It is not recommended to maintain clean-up code (Resource Deallocating Code or Resource Releasing Code) inside the try block, because there is no guarantee that every statement inside the try block will always be executed.

Similarly, it is not recommended to maintain clean-up code inside the except block, because if there is no exception, then the except block will not be executed.

Hence, we require some place to maintain clean-up code that should be executed always, irrespective of:

  • whether an exception is raised or not,
  • whether the exception is handled or not handled.

Such a place is the finally block.

Purpose of the finally Block

  • Maintain clean-up code.
  • Release resources.
  • Close files.
  • Close database connections.
  • Release network resources.
  • Execute important statements before program termination.

General Syntax

🐍Code Cell
1try:
2 # Risky Code
3 
4except:
5 # Handling Code
6 
7finally:
8 # Cleanup Code
Output
No output captured.

Speciality of finally

The speciality of the finally block is:

  • It will be executed whether an exception is raised or not raised.
  • It will be executed whether the exception is handled or not handled.

Case 1 : No Exception

If no exception occurs inside the try block, the finally block is still executed.

🐍Code Cell
1try:
2 print("try")
3except:
4 print("except")
5finally:
6 print("finally")
Output
try
finally

Case 2 : Exception Raised and Handled

If an exception occurs inside the try block and a matching except block is available, the exception is handled first, and after that the finally block executes.

🐍Code Cell
1try:
2 print("try")
3 print(10/0)
4 
5except ZeroDivisionError:
6 print("except")
7 
8finally:
9 print("finally")
Output
try
except
finally

Case 3 : Exception Raised but Not Handled

If an exception occurs inside the try block but there is no matching except block, Python still executes the finally block before terminating the program.

🐍Code Cell
1try:
2 print("try")
3 print(10/0)
4 
5except NameError:
6 print("except")
7 
8finally:
9 print("finally")
Output
try
finally
ZeroDivisionError: division by zero

Explanation

  • In Case 1, no exception occurs, so the except block is skipped and only try and finally run.
  • In Case 2, 10/0 raises a ZeroDivisionError, the matching except block handles it, and then finally runs.
  • In Case 3, 10/0 raises a ZeroDivisionError but only a NameError handler exists. The finally block still runs, and only after it does Python terminate the program abnormally.

Comparison of the Three Cases

Case Exception except Block finally Block
Case 1 - No Exception No Skipped Executed
Case 2 - Handled Yes Executed Executed
Case 3 - Not Handled Yes Skipped Executed

Execution Flow

Program Starts
      │
      ▼
Execute try Block
      │
      ▼
Exception ?
 ┌────┴────┐
 │         │
No         Yes
 │         │
 ▼         ▼
Skip or   Matching
Run       except?
 except      │
 │      ┌────┴────┐
 │      │         │
 │      ▼         ▼
 │   Handled   Not Handled
 │      │         │
 └──────┼─────────┘
        │
        ▼
Execute finally Block
        │
        ▼
Program Ends
(After finally, an unhandled
exception still terminates the
program abnormally)
      

Key Observations

  1. The finally block is mainly used for clean-up code.
  2. It executes even if no exception occurs.
  3. It also executes after a handled exception.
  4. It even executes before an unhandled exception terminates the program.
  5. Resource releasing code should normally be written inside the finally block.

Important Note - When finally is NOT Executed

There is only one situation where the finally block will not be executed.

It is when we use:

os._exit(0)

Whenever os._exit(0) is executed, the Python Virtual Machine (PVM) itself is shut down, so the finally block will not execute.

Example Using os._exit(0)

Here, 0 represents the status code, which indicates normal termination.

Because the PVM is shut down directly, finally is not printed.

🐍Code Cell
1import os
2 
3try:
4 print("try")
5 os._exit(0)
6 
7except NameError:
8 print("except")
9 
10finally:
11 print("finally")
Output
No output captured.

else Block with try-except-finally

We can use the else block with try-except-finally blocks.

The else block will be executed if and only if there are no exceptions inside the try block.

🐍Code Cell
1try:
2 # Risky Code
3 
4except:
5 # Executed if an exception occurs inside try
6 
7else:
8 # Executed only if there is no exception inside try
9 
10finally:
11 # Executed whether exception is raised or not,
12 # and whether it is handled or not handled
Output
No output captured.

Purpose of the else Block

  • Execute code only when the try block completes successfully.
  • Separate normal execution code from exception handling code.
  • Improve readability of the program.
  • Avoid writing normal statements inside the try block unnecessarily.

Example

🐍Code Cell
1try:
2 print("try")
3 print(10/0) # ---> 1
4 
5except:
6 print("except")
7 
8else:
9 print("else")
10 
11finally:
12 print("finally")
Output
No output captured.

Case 1 : No Exception

If we comment line-1 (print(10/0)), then there is no exception inside the try block:

try
else
finally

Case 2 : Exception Occurs

If we do not comment line-1 (print(10/0)), then an exception occurs inside the try block:

try
except
finally

Comparison

Situation except else finally
No Exception Skipped Executed Executed
Exception Occurs Executed Skipped Executed

Rules of try-except-else-finally

  1. Whenever we write a try block, we must write either an except block or a finally block.
  2. An except block must always be associated with a try block.
  3. A finally block must always be associated with a try block.
  4. We can write multiple except blocks for one try block, but not multiple finally blocks.
  5. Whenever we write an else block, an except block must also be present.
  6. The order of the blocks is important: tryexceptelsefinally.
  7. We can define these blocks inside try, except, else, or finally — nesting is always possible.

Valid and Invalid Combinations

Combination Valid / Invalid
try only ❌ Invalid
except only ❌ Invalid
else only ❌ Invalid
finally only ❌ Invalid
try + except ✅ Valid
try + finally ✅ Valid
try + except + else ✅ Valid
try + except + finally ✅ Valid
try + except + else + finally ✅ Valid
📝 Key Takeaways
  • finally is meant for clean-up and resource-releasing code
  • finally executes whether or not an exception is raised or handled
  • The else block runs only when the try block completes without any exception
  • os._exit(0) shuts down the PVM directly, so finally is the single case that does not run
  • The correct block order is try, except, else, finally

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10