Open In App

Finally keyword in Python

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, the finally keyword is used in a try-except-finally block to define a section of code that will always execute, regardless of whether an exception occurs or not. It guarantees predictable code behavior, maintaining program stability even when errors arise. By using finally, developers ensure that cleanup operations and essential tasks are consistently performed, promoting code reliability and readability.

Example:

Python
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Caught division by zero error.")
finally:
    print("This block always executes.")

Output
Caught division by zero error.
This block always executes.

Important Points

  • finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block.
  • finally block is used to deallocate the system resources.
  • One can use finally just after try without using except block, but no exception is handled in that case.

Syntax

try:
# Code that may raise an exception
except ExceptionType:
# Code that handles the exception
finally:
# Code that always executes

  • Parameters: finally block does not accept any parameters.
  • Return type: finally block does not return any value; it is used solely for executing cleanup code.

Examples

Example 1: Handling ZeroDivisionError

This example demonstrates the finally block executing after an exception is raised and handled.

Python
try:
    k = 5 // 0
except ZeroDivisionError:
    print("Can't divide by zero")
finally:
    print('This is always executed')

Output
Can't divide by zero
This is always executed

Explanation: The ZeroDivisionError is caught in the except block, printing a message. Regardless of the exception, the finally block executes, ensuring that the cleanup or final statement runs.

Example 2: No Exception Occurs

This example shows that the finally block executes even when no exception occurs.

Python
try:
    k = 5 // 1
    print(k)
finally:
    print('This is always executed')

Output
5
This is always executed

Explanation: The try block executes without any errors, so the except block is skipped. However, the finally block still runs, demonstrating its unconditional execution.

Example 3: Unhandled Exception

In this example, the exception is not caught, but the finally block still executes.

Python
try:
    k = 5 // 0
finally:
    print('This is always executed')
Screenshot-2025-02-22-153635

Unhandled Exception

Explanation: The division by zero causes a ZeroDivisionError, which is not handled. Despite this, the finally block executes before the program terminates with an error.

Example 4: Interaction with Return Statement

This example shows that the finally block executes before the return statement.

Python
def learnfinally():
    try:
        print("Inside try Block")
        return 1
    finally:
        print("Inside Finally")

print(learnfinally())

Output
Inside try Block
Inside Finally
1

Explanation: Although the try block has a return statement, the finally block executes before the function returns the value. This demonstrates that finally has priority over control flow statements like return.



Next Article
Article Tags :
Practice Tags :

Similar Reads