Basic try-except
Use try and except to catch and handle errors:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
result = None
Multiple exceptions
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else clause
else runs if no exception occurred:
try:
result = 10 / 2
except ZeroDivisionError:
print("Error!")
else:
print(f"Result: {result}") # Only runs if no error
finally clause
finally always runs, whether there was an error or not:
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
file.close() # Always closes, even if error occurred
Raising exceptions
You can raise your own exceptions:
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age seems unrealistic")
return age
try:
check_age(-5)
except ValueError as e:
print(e) # "Age cannot be negative"