What is the finally keyword in Python?

The finally block is an optional part of Python exception handling that is executed regardless of whether an exception occurs or not.

It is commonly used for cleanup operations, such as:

Basic Syntax

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

Important Notes

Execution Flow

Python executes blocks in the following order:

Example

Python

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Number entered is not an integer.")
else:
    print("Integer Accepted.")
finally:
    print("This block is always executed.")    

Output 1:

Output

Enter an integer: 19
Integer Accepted.
This block is always executed.    

Output 2:

Output

Enter an integer: 3.142
Number entered is not an integer.
This block is always executed.    

Example: finally with return

The finally block is very important when a function returns a value.

Python

def divide(a, b):
    try:
        return a / b  # Return statement in try
    except ZeroDivisionError:
        return "Cannot divide by zero"
    finally:
        print("Function execution completed.")  # Always runs    

Explanation