Question
What is the use of the finally block?
Solution
β Verified
The finally block in Python is used to define cleanup actions that must be executed under all circumstances, regardless of whether an exception was raised or not in the try block.
Key Uses of finally:
- Releasing resources (e.g., closing files, database connections, or network sockets)
- Executing important code that must run no matter what (e.g., logging, status updates)
try:
file = open('example.txt', 'r')
data = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed.")
In this example, the file is closed even if an exception occurs while trying to open or read it. This ensures proper resource management.
Click here to download practice questions on
Exception Handling in PythonMore Questions on Exception Handling in Python
Question 6
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
View solution