User-defined Exceptions in Python with Examples
Last Updated :
22 Jul, 2025
User-defined exceptions are created by defining a new class that inherits from Python's built-in Exception class or one of its subclasses. By doing this, we can create custom error messages and handle specific errors in a way that makes sense for our application.
Steps to Create and Use User-Defined Exceptions
- Define a New Exception Class: Create a new class that inherits from Exception or any of its subclasses.
- Raise the Exception: Use the raise statement to raise the user-defined exception when a specific condition occurs.
- Handle the Exception: Use try-except blocks to handle the user-defined exception.
Example of a User-Defined Exception:
Python
# Step 1: Define a custom exception class
class InvalidAgeError(Exception):
def __init__(self, age, msg="Age must be between 0 and 120"):
self.age = age
self.msg = msg
super().__init__(self.msg)
def __str__(self):
return f'{self.age} -> {self.msg}'
# Step 2: Use the custom exception in your code
def set_age(age):
if age < 0 or age > 120:
raise InvalidAgeError(age)
else:
print(f"Age set to: {age}")
# Step 3: Handling the custom exception
try:
set_age(150) # This will raise the custom exception
except InvalidAgeError as e:
print(e)
Output150 -> Age must be between 0 and 120
Explanation:
- InvalidAgeError class inherits from Exception. It has an __init__ method that takes an age and an optional message. __str__ method returns a string that will be shown when the exception is printed.
- In the set_age function, we check if the age is outside the valid range (0–120). If it is, we raise the InvalidAgeError.
- We use a try-except block to catch and handle the InvalidAgeError. When this error is raised, the error message is printed.
Customizing Exception Classes
When we create a custom exception, we subclass Python’s built-in Exception class (or a subclass like ValueError, TypeError, etc.). We can then add our own attributes, methods or custom logic to make our exception more informative.
Python
# Step 1: Subclass the Exception class
class InvalidAgeError(Exception):
def __init__(self, age, msg="Age must be between 0 and 120", error_code=1001):
# Custom attributes
self.age = age
self.msg = msg
self.error_code = error_code
super().__init__(self.msg) # Call the base class constructor
# Step 2: Customize the string representation of the exception
def __str__(self):
return f"[Error Code {self.error_code}] {self.age} -> {self.msg}"
# Step 3: Raising the custom exception
def set_age(age):
if age < 0 or age > 120:
raise InvalidAgeError(age)
else:
print(f"Age set to: {age}")
# Step 4: Handling the custom exception with additional information
try:
set_age(150) # This will raise the custom exception
except InvalidAgeError as e:
print(e)
Output[Error Code 1001] 150 -> Age must be between 0 and 120
Explanation:
- __str__ method is overridden to provide a custom error message when the exception is printed. Message includes the error code and age, making it more informative.
- In the set_age function, if the age is invalid, the custom exception InvalidAgeError is raised. Exception is then caught in the try-except block, and the customized error message is printed.
How to use standard Exceptions as a base class?
A runtime error is a class that is a standard exception that is raised when a generated error does not fall into any category. This program illustrates how to use runtime error as a base class and network error as a derived class. In a similar way, an exception can be derived from the standard exceptions of Python.
Python
# NetworkError has base RuntimeError and not Exception
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise Networkerror("Error")
except Networkerror as e:
print(e.args)
Output
('E', 'r', 'r', 'o', 'r')