Errors

Custom Exceptions

Custom exception classes name failures that belong to your domain.

Create a custom exception when a failure has a name in your problem domain. The class can be empty at first.

Source

class EmptyCartError(Exception):
    pass

print(EmptyCartError.__name__)

Output

EmptyCartError
BaseExceptionExceptionValueErrorMyDomainError
Subclassing an existing exception gains a domain name without changing semantics.

Raise the custom exception where the invalid state is detected. Normal inputs still follow the ordinary success path.

Source

def checkout(items):
    if not items:
        raise EmptyCartError("cart is empty")
    return "paid"

print(checkout(["book"]))

Output

paid

Callers can catch the precise error type without accidentally catching unrelated failures.

Source

try:
    checkout([])
except EmptyCartError as error:
    print(error)

Output

cart is empty

Notes

See also

Run the complete example

Example code

Expected output

EmptyCartError
paid
cart is empty

Execution time appears here after you run the example.