The finally keyword is used with the try statement to define a block of code that always executes, whether an exception occurs or not. It is commonly used to perform cleanup tasks, such as closing files, releasing resources, or executing code that must run before the program continues.
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.
Explanation: try block raises a ZeroDivisionError, which is handled by the except block. After that, the finally block executes, showing that it always runs regardless of whether an exception occurs.
Syntax
The general syntax of the finally keyword is shown below:
try:
# code that may raise an exception
except ExceptionType:
# handle the exception
finally:
# code that always executes
Examples
Example 1: Here, we use the finally block with a try block to show that it executes even when no except block is present.
try:
print("Inside try block")
finally:
print("Inside finally block")
Output
Inside try block Inside finally block
Explanation: No exception occurs, so the try block executes normally. After that, the finally block executes.
Example 2: Here, the try block executes successfully without raising an exception, and the finally block runs afterward.
try:
result = 10 + 20
print(result)
finally:
print("Execution completed")
Output
30 Execution completed
Explanation: try block executes successfully without raising an exception. The finally block still runs after it.
Example 3: Here, we write data to a file and use the finally block to close the file after the operation is completed.
file = open("sample.txt", "w")
try:
file.write("Hello, Python!")
finally:
file.close()
print("File closed")
Output
File closed
Explanation: file is closed in the finally block, ensuring that the resource is released after use.
Example 4: Here, we use a return statement inside the try block to demonstrate that the finally block executes before the function returns.
def show():
try:
return "Inside try"
finally:
print("Inside finally")
print(show())
Output
Inside finally Inside try
Explanation: Although the try block contains a return statement, the finally block executes before the function returns the value.