When Python encounters an error, the interpreter stops executing the current block of code and looks for an appropriate handler to address the exception. If no handler is found, the program terminates.
If an exception isn’t caught, Python provides a default handler that:
Python allows you to handle exceptions using try and except blocks. This structure lets you execute a block of code and catch exceptions that may arise, providing specific responses for different errors.
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
else Clause: Executes if no exceptions are raised in the try block.finally Clause: Executes regardless of whether an exception occurred, often used for cleanup tasks.try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
file.close()