typestar

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

  1. EmptyCartError subclasses Exception in one line.
  2. raise aborts checkout with a specific, catchable type.
  3. The caller handles it separately from generic errors.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 7 in Iterators, errors & files, step 48 of 72 in Language basics.

← Previous Next →