defdivide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(f"Error: {e}")
# Raise with a messagedefvalidate_age(age):
ifnotisinstance(age, int):
raise TypeError("Age must be an integer")
if age < 0or age > 150:
raise ValueError(f"Age {age} is out of range")
return age
try:
validate_age(-5)
except ValueError as e:
print(f"Validation: {e}")
Output
Click "Run" to execute your code
raise creates and throws an exception. Always include a descriptive message to help with debugging.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?