Raising custom exceptions in Python
Naming your failure modes with your own exception class.
class EmptyCartError(Exception):
pass
def checkout(cart):
if not cart:
raise EmptyCartError("nothing to buy")
if any(price < 0 for price in cart.values()):
raise ValueError("negative price")
return sum(cart.values())
try:
total = checkout({})
except EmptyCartError as exc:
total = 0
How it works
EmptyCartErrorsubclassesExceptionin one line.raiseaborts checkout with a specific, catchable type.- The caller handles it separately from generic errors.
Keywords and builtins used here
EmptyCartErroranyascheckoutclassdefexceptforifpassraisereturnsumtry
The run, in numbers
- Lines
- 16
- Characters to type
- 286
- Tokens
- 73
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 44 seconds.
Step 5 of 7 in Iterators, errors & files, step 48 of 72 in Language basics.