How do I create and use custom exceptions in Python?
· Category: Python Programming
Short answer
Create custom exceptions by subclassing Exception or one of its subclasses. This makes your errors self-documenting and allows callers to catch them precisely.
Steps
- Define a class that inherits from
Exception. - Optionally override
__init__to accept custom data. - Raise the exception with
raise MyException("message").
class ValidationError(Exception):
"""Raised when input data fails validation."""
pass
class NegativeValueError(ValidationError):
def __init__(self, value):
self.value = value
super().__init__(f"Value must be non-negative, got {value}")
def set_age(age):
if age < 0:
raise NegativeValueError(age)
return age
try:
set_age(-5)
except NegativeValueError as e:
print(e)
Tips
- Inherit from
Exceptionrather thanBaseExceptionunless you are writing a system-level exception. - Group related custom exceptions under a common base class so callers can catch the whole family.
- Include relevant context in exception arguments to aid debugging.
Common issues
- Naming a custom exception
Errorwithout a descriptive prefix makes it ambiguous. - Overusing custom exceptions for every minor condition clutters the codebase; use built-ins when they fit.
- Forgetting to call
super().__init__()can cause issues with exception chaining and args.