PythonException Handling
Finally Block
What Is the finally Block?
The finally block:
- Always executes
- Runs whether an exception occurs or not
- Is used for cleanup operations
finally block is important when working with:
- Files
- Database connections
- Network resources
It is the developer’s responsibility to close resources properly.
Syntax
try:
risky_code
except ExceptionType:
handling_code
finally:
cleanup_code
Example with finally block
print("Resource opened successfully")
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result is:", result)
except ZeroDivisionError as zde:
print("Division by zero is not allowed.", zde)
except ValueError as ve:
print("Invalid input.", ve)
finally:
print("Resource closed.")
print("End of execution")Output
Resource opened successfully
Enter numerator: 4
Enter denominator: 0
Division by zero is not allowed. division by zero
Resource closed.
End of executionfinally Executes Even Without except
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print(a / b)
finally:
print("Resource closed.")Output
Enter numerator: 4
Enter denominator: t
Resource closed.
ValueError: invalid literal for int()Summary
- The
finallyblock always executes, regardless of whether an exception occurs or not. - It is primarily used for resource cleanup, such as closing files or database connections.
- Resources must be released explicitly by the developer to avoid memory leaks and system issues.
- A
tryblock must be followed by at least oneexceptor afinallyblock. - Using
finallyensures program stability and proper resource management in real-world applications.
Written By: Muskan Garg
How is this guide?
Last updated on
