A custom exception is a user-defined exception class, created by inheriting from Exception or one of its subclasses. Custom exceptions let you represent domain-specific error conditions — InsufficientFundsError, ConfigurationError, AuthenticationFailedError — that are more meaningful than generic built-in exceptions.
The simplest custom exception is just an empty class: class InsufficientFundsError(Exception): pass. For richer exceptions, override __init__ to accept additional data: class ValidationError(Exception): def __init__(self, field, message): .... Custom exceptions should always inherit from Exception (not BaseException) so that except Exception: catches them appropriately.
A well-designed library defines a base exception class (class MyLibError(Exception): pass) and derives specific exceptions from it (class ConnectionError(MyLibError): pass, class TimeoutError(MyLibError): pass). This lets callers catch all library errors with except MyLibError: or specific ones with except TimeoutError:. The exception hierarchy mirrors the error taxonomy of the domain, making error handling precise and self-documenting.
Related terms: Exception, Exception Hierarchy, Try/Except
Discussed in:
- Chapter 11: Error Handling — Custom Exception Classes