Custom exceptions provide a way to handle specific error scenarios unique to your application. They enhance code readability and make debugging easier.
To create a custom exception, define a new class that inherits from the Exception
base class.
class MyCustomError(Exception):
"""Custom exception for specific error handling."""
pass
You can add attributes to your custom exception to store additional information about the error.
class InvalidInputError(Exception):
def __init__(self, input_value, message="Invalid input provided"):
self.input_value = input_value
self.message = message
super().__init__(self.message)
You can raise custom exceptions in your code when specific conditions are met.
def validate_age(age):
if age < 0:
raise InvalidInputError(age, "Age cannot be negative.")
Handle custom exceptions using a try-except block.
try:
validate_age(-1)
except InvalidInputError as e:
print(f"Error: {e.message} (Input: {e.input_value})")
You can create a hierarchy of custom exceptions to handle various error types within an application.
class ApplicationError(Exception):
"""Base class for other exceptions"""
pass
class DatabaseError(ApplicationError):
"""Raised for database-related errors"""
pass
class ValidationError(ApplicationError):
"""Raised for validation errors"""
pass