![]() |
VOOZH | about |
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.
Follow these steps to create and use User-Defined Exceptions in Python:
Example: In this example, we create a custom exception InvalidAgeError to ensure that age values fall within a valid range (0–120).
150 -> Age must be between 0 and 120
Explanation:
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.
We can also enhance custom exceptions by adding extra attributes or overriding methods.
Example: Here, we improve the InvalidAgeError by adding an error code and customizing the error message.
[Error Code 1001] 150 -> Age must be between 0 and 120
Explanation:
Sometimes, instead of directly inheriting from Exception, we can create a custom exception by subclassing a standard exception such as RuntimeError, ValueError, etc. This is useful when your custom exception should be treated as a specific kind of error.
Example: This example shows how to create a custom exception NetworkError by inheriting from RuntimeError, which is a standard built-in exception.
('Connection failed',)
Explanation:
Here’s a simple example where we raise a custom exception if the email address is not valid:
userexample.com -> Invalid email format
Explanation:
User-defined exceptions should be considered in the following scenarios:
By using user-defined exceptions, programs become more readable, maintainable and easier to debug.