14. Custom Exceptions
These examples show how to design custom exception classes for specific error-handling scenarios, allowing for more granular and meaningful error reporting in your Python applications.
class MyCustomError(Exception):
pass
def divide(a, b):
if b == 0:
raise MyCustomError("Cannot divide by zero!")
return a / b
try:
result = divide(10, 0)
except MyCustomError as e:
print(f"Error: {e}")class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be greater than 0"):
self.age = age
self.message = message
super().__init__(self.message)
def validate_age(age):
if age <= 0:
raise InvalidAgeError(age)
print(f"Age {age} is valid.")
try:
validate_age(0)
except InvalidAgeError as e:
print(f"Error: {e}")Last updated