Exception Handling
Python uses try
, except
, else
, and finally
blocks to handle exceptions.
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero:", e)
else:
print("Division successful")
finally:
print("This block always executes")
This helps to prevent crashes and handle unexpected errors gracefully. You can catch specific exceptions or use a generic except Exception
block.