Last Updated : 11 Jul, 2025
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.")
Caught division by zero error. This block always executes.
Important Points -
try:
# Code that may raise an exception
except ExceptionType:
# Code that handles the exception
finally:
# Code that always executes
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')
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 OccursThis example shows that the finally
block executes even when no exception occurs.
try:
k = 5 // 1
print(k)
finally:
print('This is always executed')
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.
In this example, the exception is not caught, but the finally
block still executes.
try:
k = 5 // 0
finally:
print('This is always executed')
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.
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())
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
.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4