The Exception Handling Dance
Python's scaffolding for handling exceptions encompasses try, except, else, and finally blocks.
The try block encloses potentially problematic code, ready to trigger exceptions. When an exception occurs within this block, control shifts to an associated except block.
try:
# Code susceptible to exceptions
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
In this scenario, the ZeroDivisionError is apprehended by the except block, forestalling program collapse.
In case no exceptions arise within the try block, the else block executes, housing code intended for normal execution.
try:
result = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print("You entered:", result)
The finally block unfailingly executes, irrespective of exceptions, facilitating resource cleanup or finalization.
try:
file = open("example.txt", "r")
# Perform file operations
except FileNotFoundError:
print("File not found!")
finally:
file.close() # Ensure proper closure