How does the finally block work in Python exception handling?
a) Executes code regardless of whether an exception occurs
b) Executes only if an exception occurs
c) Executes only if no exceptions occur
d) Used to raise an exception manually
Answer:
a) Executes code regardless of whether an exception occurs
Explanation:
The finally
block in Python exception handling is used to execute code that should run regardless of whether an exception occurs or not. This block is typically used for cleaning up resources, such as closing files or releasing network connections, ensuring that they are properly handled even if an error occurs.
try:
# Code that might raise an exception
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
# Code to handle the exception
print("File not found!")
finally:
# Code to always execute, such as closing the file
file.close()
print("File closed.")
In this example, the finally
block ensures that the file is closed whether or not an exception occurs. If the file is not found, the except
block will handle the error, but the finally
block will still execute to close the file.
The finally
block is essential for resource management, helping to avoid resource leaks and ensuring that necessary cleanup is always performed.