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.


I do trust all of the concepts you’ve presented to your post. They are very convincing and can definitely work. Still, the posts are too brief for beginners. May just you please extend them a bit from next time? Thank you for the post.
Hôm qua vừa làm vài vòng bet888 slot ở Bet188vina. Phải nói là phê chữ ê kéo dài luôn! Game nó đa dạng, mà quay trúng liên tục. Tui nạp có xíu mà ăn được kha khá đó!
Hi my friend! I wish to say that this article is amazing, nice written and include almost all significant infos. I’d like to see more posts like this.