Errors
Custom Exceptions
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
EmptyCartErrorRaise 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
paidCallers can catch the precise error type without accidentally catching unrelated failures.
Source
try:
checkout([])
except EmptyCartError as error:
print(error)Output
cart is emptyNotes
- Subclass
Exceptionfor errors callers are expected to catch. - A custom exception name can be clearer than reusing a generic
ValueErroreverywhere. - Catch custom exceptions at a boundary that can recover or report clearly.
See also
- related: Exceptions
- related: Exception Chaining
- related: Warnings
- next depth: Logging
Run the complete example
Expected output
EmptyCartError
paid
cart is empty
Execution time appears here after you run the example.