Finally Block

The finally block is used in exception handling.
It always executes — whether an error occurs or not.

It is mainly used for cleanup tasks such as:

  • Closing files
  • Releasing resources
  • Closing database connections

BASIC SYNTAX

try:
# risky code
except:
# handle error
finally:
# always runs

The finally block runs no matter what happens in the try block.

SIMPLE EXAMPLE

try:
print(10 / 2)
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")

Output:

5.0
Execution completed.

Even though no error occurred, finally still executed.

EXAMPLE WITH ERROR

try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")

Output:

Cannot divide by zero.
Execution completed.

The finally block runs even when an error occurs.

FINALLY WITH FILE HANDLING

try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
print("File operation finished.")

Even if the file does not exist, the finally block runs.

TRY – EXCEPT – ELSE – FINALLY STRUCTURE

try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print("You entered:", num)
finally:
print("Program ended.")

Execution order:

  • try runs first
  • If error → except runs
  • If no error → else runs
  • finally always runs

IMPORTANT POINTS

finally always executes
• Used for cleanup tasks
• Works with or without except
• Commonly used in file and database operations

KEY TAKEAWAY

The finally block ensures important code runs no matter what happens, making your Python programs safer and more reliable.

Home » PYTHON INTERMEDIATE (PYI) > Exception Handling > Finally Block