Python

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.

© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)