Introduction
Python provides a rich set of built-in exceptions to handle common errors in programming,
but for specific situations in your application, defining your own custom exceptions improves
readability, maintainability, and debugging capabilities. Custom exceptions allow developers
to create error hierarchies and more meaningful exception messages.
Objective
In this tutorial, you’ll learn how to create and use custom exceptions in Python.
We’ll walk through the syntax, create a sample custom exception class, raise the exception,
and handle it gracefully using try-except blocks.
Python Code to Create a Custom Exception
# Define a custom exception class
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 1 and 120."):
self.age = age
self.message = message
super().__init__(self.message)
def __str__(self):
return f"InvalidAgeError: {self.age} -> {self.message}"
# Function that uses the custom exception
def validate_age(age):
if age < 1 or age > 120:
raise InvalidAgeError(age)
else:
print(f"Age {age} is valid.")
# Main block to test the custom exception
if __name__ == "__main__":
try:
user_input = int(input("Enter your age: "))
validate_age(user_input)
except InvalidAgeError as e:
print(e)
except ValueError:
print("Please enter a valid integer.")
Explanation of the Program Structure
1. Custom Exception Class:
InvalidAgeError
is a subclass of Python’s built-in Exception
class.
It accepts an age
and an optional message
, which is passed to the base class using super()
.
2. Raising the Exception:
The function validate_age()
checks if the age is within a valid range. If not, it raises the InvalidAgeError
.
3. Exception Handling:
The try-except
block captures the custom exception and prints a helpful message using the __str__()
method.
It also handles invalid input types such as strings or special characters by catching ValueError
.
How to Run the Program
1. Copy the above code into a Python file, e.g., custom_exception.py
.
2. Run the file using a Python interpreter: python custom_exception.py
3. Enter an age when prompted. Try inputs like -5
, 200
, or a valid age like 30
to see different outcomes.