7.4 Custom Exceptions
Creating our own custom exceptions by inheriting from the Exception class to represent specific application errors.
To make your code more readable and error handling more specific, you can create your own custom exceptions. This is done simply by defining a new class that inherits from Python's built-in `Exception` class. Creating custom exceptions allows you and other programmers to immediately understand what kind of error has occurred, especially in large projects.
# Creating a custom exception
class InvalidAgeError(Exception):
"""Raised when the age is outside the valid range."""
pass
def check_age_for_entry(age):
if not 18 <= age <= 100:
raise InvalidAgeError(f"Age {age} is out of bounds (18-100).")
print("Age is valid.")
try:
check_age_for_entry(25) # OK
check_age_for_entry(15) # Will raise an error
except InvalidAgeError as e:
print(f"Caught Custom Error: {e}")
Practical Exercises
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.