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:
- Closing files
- Closing database connections
- Releasing system resources
- Printing final status messages
Basic Syntax
try:
# Code that may raise an exception
except:
# Code that handles the exception
finally:
# Code that always executes Important Notes
- The finally block always runs, even if an exception occurs.
- The finally block runs even if no exception occurs.
- The finally block runs even if a return statement is executed.
- It executes after try and except blocks.
Execution Flow
Python executes blocks in the following order:
- try block
- except block (if an error occurs)
- else block (if no error occurs, optional)
- finally block (always)
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
- Even if return executes, the finally block still runs.
- It is useful for logging, cleanup, and closing resources.