In this Python Exception Handling Tutorial series we'll see how to create user defined exceptions in Python which allow developers to create custom error types tailored to specific scenarios.
While Python provides a wide range of built‑in exceptions (like ValueError, TypeError, and IndexError), sometimes you as a user would want to create your own exception for a specific scenario in order to make error messages more relevant to the context. Such exceptions are called user-defined exceptions or custom exceptions. Defining your own exception makes error handling more meaningful and easier to debug.
User-defined exception in Python
To create a custom exception in Python, you simply define a new class that inherits from the built‑in Exception class (directly or indirectly).
Since your exception class is a class it can theoretically be defined to do anything any other class can do, but usually user-defined exception classes are kept simple, providing just enough information for handlers to understand the error.
As a convention, custom exception names should end with "Error", following the style of Python’s standard exceptions. This makes your code more readable and consistent with community practices.
User-defined exception Python example
Suppose you have a Python function that take age as a parameter and tells whether a person is eligible to vote or not. Voting age is 18 or more.
If person is not eligible to vote you want to raise an exception using raise statement, for this scenario you want to write a custom exception named “InvalidAgeError”.
# Custom exception
class InvalidAgeError(Exception):
"""Raised when the age provided is invalid."""
def __init__(self, arg):
self.msg = arg
def vote_eligibility(age):
if age < 18:
raise InvalidAgeError("Person not eligible to vote, age is " + str(age))
else:
print('Person can vote, age is', age)
# calling function
try:
vote_eligibility(22)
vote_eligibility(14)
except InvalidAgeError as error:
print(error)
Output
Person can vote, age is 22 Person not eligible to vote, age is 14
Hierarchical custom exceptions
When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
That's all for this topic How to Create User-defined Exceptions in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-