43. Creating Custom Python Exceptions
Here are 10 Python code snippets demonstrating how to create custom exceptions, which allow for more specialized and accurate error handling:
1. Basic Custom Exception
Define a basic custom exception by subclassing Exception.
class CustomError(Exception):
pass
raise CustomError("This is a custom error.")This creates a basic custom exception called CustomError.
2. Custom Exception with Error Message
You can add a custom message to your exception.
class InvalidAgeError(Exception):
def __init__(self, message="Age must be between 0 and 120"):
self.message = message
super().__init__(self.message)
raise InvalidAgeError("Invalid age provided.")This exception class includes an initialization method that accepts a custom error message.
3. Custom Exception with Additional Attributes
Custom exceptions can store additional data for better context.
This custom exception includes the database name along with the error message.
4. Custom Exception with Logging
You can create an exception that logs the error when raised.
This logs the error message when the exception is raised.
5. Custom Exception with Custom String Representation
Override the __str__ method to customize the exception string.
This custom exception provides a specialized string representation when printed.
6. Custom Exception with __repr__ for Debugging
Override the __repr__ method for better debugging output.
The __repr__ method provides a more detailed output for debugging purposes.
7. Custom Exception with Multiple Constructors
Create custom exceptions with multiple ways to initialize.
This example allows creating the exception either from a filename or with a default message.
8. Custom Exception for Specific Use Case (Input Validation)
A custom exception can be designed for input validation scenarios.
This custom exception inherits from ValueError and adds a specific error message for invalid inputs.
9. Custom Exception for Resource Not Found
Design a custom exception for when a resource is not found.
This exception could be raised when a resource (e.g., a file, database record) cannot be found.
10. Custom Exception with a Stack Trace
Capture the stack trace when raising a custom exception for debugging purposes.
This custom exception logs the stack trace when it’s raised.
These custom exception examples can be used to add more specific, helpful, and organized error handling in your Python applications, making the debugging and error logging process more robust.
Last updated