43. Creating Custom Python Exceptions
1. Basic Custom Exception
class CustomError(Exception):
pass
raise CustomError("This is a custom error.")2. Custom Exception with Error Message
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.")3. Custom Exception with Additional Attributes
4. Custom Exception with Logging
5. Custom Exception with Custom String Representation
6. Custom Exception with __repr__ for Debugging
__repr__ for Debugging7. Custom Exception with Multiple Constructors
8. Custom Exception for Specific Use Case (Input Validation)
9. Custom Exception for Resource Not Found
10. Custom Exception with a Stack Trace
Last updated