Finally keyword is used with try and except blocks to define code that always executes, whether an exception occurs or not. It is commonly used for cleanup tasks such as closing files or releasing resources.
Example:
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.
- The finally block is used to release system resources.
- The finally block can be used directly with try even without an except block.
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.
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.
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.
try:
k = 5 // 0
finally:
print('This is always executed')

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.
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 the finally block executes before the function returns a value.