Sometimes, we want to declare custom exceptions in Python.
In this article, we’ll look at how to declare custom exceptions in Python.
How to declare custom exceptions in Python?
To declare custom exceptions in Python, we can create a subclass of the Exception
class.
For instance, we write
class ValidationError(Exception):
def __init__(self, message, errors):
super().__init__(message)
self.errors = errors
to create the ValidationError
exception class that’s a subclass of Exception
.
In the __init__
method, we call the Exception
constructor with
super().__init__(message)
Then we add custom code after that like
self.errors = errors
Conclusion
To declare custom exceptions in Python, we can create a subclass of the Exception
class.