Finally Keyword in Python
The finally
block in Python is used to execute code, regardless of the result of the try
and except
blocks. It is useful for cleaning up resources, such as closing files or releasing locks, even if an error occurs.
1. Basic Use of Finally
Using the finally
block ensures that the code inside it will run no matter what.
# Example of finally
try:
file = open('example.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print("File closed.")
# Output:
# File not found!
# File closed.
2. Finally with No Exceptions
The finally
block executes even if no exceptions are raised in the try
block.
# Example where no exception is raised
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute")
# Output:
# This will always execute
3. Finally with Exception Handling
The finally
block executes whether an exception occurs or not.
# Example with an exception and finally
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always execute")
# Output:
# Cannot divide by zero!
# This will always execute
4. Finally with Else
The else
block executes if no exceptions are raised, and the finally
block executes in both cases.
# Example with try, except, else, and finally
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("The result is", result)
finally:
print("This will always execute")
# Output:
# The result is 5.0
# This will always execute