Skip to content

Errors and validation

Money tasks read amounts from strings, files and other services. Sooner or later the interviewer asks: “What if the amount is empty, or ‘abc’, or negative?” A function that quietly returns 0 is worse than one that crashes, because a payout of 0 looks valid.

The boundary is the place where outside data becomes your data: an API handler, a CSV reader, a webhook. Check everything there once. Then the inner functions can trust their arguments and stay short. A webhook payload with the fields of webhook_events:

from datetime import datetime
EVENT_TYPES = {"purchase", "renewal", "expiration", "refund"}
def parse_event(raw: dict) -> dict:
missing = {"event_id", "type", "occurred_at"} - raw.keys()
if missing:
raise ValueError(f"missing fields: {sorted(missing)}")
if raw["type"] not in EVENT_TYPES:
raise ValueError(f"unknown event type: {raw['type']!r}")
return {
"event_id": raw["event_id"],
"type": raw["type"],
"at": datetime.fromisoformat(raw["occurred_at"]),
}
for raw in [
{"event_id": "e1", "type": "renewal", "occurred_at": "2026-09-01T10:00:00"},
{"event_id": "e2", "type": "renewal"},
{"event_id": "e3", "type": "RENEWAL", "occurred_at": "2026-09-01T10:00:00"},
{"event_id": "e4", "type": "refund", "occurred_at": "2026-09-31T10:00:00"},
]:
try:
print(parse_event(raw))
except ValueError as e:
print("ValueError:", e)
{'event_id': 'e1', 'type': 'renewal', 'at': datetime.datetime(2026, 9, 1, 10, 0)}
ValueError: missing fields: ['occurred_at']
ValueError: unknown event type: 'RENEWAL'
ValueError: day 31 must be in range 1..30 for month 9 in year 2026

The first three messages say what is wrong and show the value. The last one comes from datetime and does not say which event or which field. At the boundary, add that context with raise ... from e (below). ValueError is the right type for “the type is fine, the value is not”. TypeError is for a wrong type, such as None where a string was expected.

Amounts come as strings, and Decimal(s) is the usual parser. It accepts more than you might expect:

from decimal import Decimal
for s in ["12.5", " 12.5 ", "1e3", "-1", "NaN", "Infinity", "abc", "", "1,5", None]:
try:
print(f"{s!r:12} -> {Decimal(s)!r}")
except Exception as e:
print(f"{s!r:12} -> {type(e).__name__}")
'12.5' -> Decimal('12.5')
' 12.5 ' -> Decimal('12.5')
'1e3' -> Decimal('1E+3')
'-1' -> Decimal('-1')
'NaN' -> Decimal('NaN')
'Infinity' -> Decimal('Infinity')
'abc' -> InvalidOperation
'' -> InvalidOperation
'1,5' -> InvalidOperation
None -> TypeError
InputWhat to do
'12.5', ' 12.5 'accept; quantize to 12.50
'abc', '', '1,5'turn InvalidOperation into ValueError
'NaN', 'Infinity'reject with is_finite()
'-1'reject if negative amounts are not allowed
'1e3'ask whether exponent notation is valid input
Nonecheck the type first, or catch the TypeError

Two details make this tricky:

from decimal import Decimal, InvalidOperation
print(issubclass(InvalidOperation, ValueError), issubclass(InvalidOperation, ArithmeticError))
print(Decimal("NaN").is_finite(), Decimal("Infinity").is_finite(), Decimal("12.5").is_finite())
print(Decimal("Infinity") > 0)
print(Decimal("NaN") < 0)
False True
False False True
True
Traceback (most recent call last):
...
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
  • InvalidOperation is an ArithmeticError, not a ValueError. So except ValueError does not catch it.
  • Infinity passes a check like amount > 0. A comparison with NaN raises InvalidOperation itself. So call is_finite() first and compare after it.

Turn a low-level error into one the caller understands, and keep the original as the cause:

from decimal import Decimal, InvalidOperation
def to_decimal(s):
try:
return Decimal(s)
except InvalidOperation as e:
raise ValueError(f"not an amount: {s!r}") from e
to_decimal("12,50")
Traceback (most recent call last):
...
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
...
ValueError: not an amount: '12,50'

The caller catches one type, ValueError, and reads a clear message. The log still shows the original error, and the code can reach it as err.__cause__. Three variants:

CodeTraceback saysUse
raise ValueError(...) from e“The above exception was the direct cause…”you translate the error on purpose
raise ValueError(...) inside except“During handling of the above exception, another exception occurred”looks like a second bug
raise ValueError(...) from Noneonly the new errorthe original adds nothing

A broad except turns bugs into wrong answers:

from decimal import Decimal
def parse_amount_bad(s):
try:
return Decimal(s.strp()) # typo: strp instead of strip
except Exception:
return Decimal("0")
print(parse_amount_bad("12.50"))
0

The typo raises AttributeError, the except swallows it, and every amount becomes 0. No test with valid input fails loudly. Rules:

  • Catch the exact type you expect: InvalidOperation, KeyError, TimeoutError.
  • Keep the try block small: only the line that can fail.
  • A bare except: also catches KeyboardInterrupt and SystemExit. Do not write it.
  • If you must catch everything (at the top of a worker loop), log the error with its traceback and re-raise or count it. Never hide it.

Define your own exception when the caller must react to it in a special way. Inherit from a built-in one when it fits, so callers that catch the built-in still work:

class PayoutError(Exception):
"""Base class: everything that can go wrong with a payout."""
class InvalidAmount(PayoutError, ValueError):
"""Bad input: retrying will not help."""
class BankUnavailable(PayoutError):
"""The bank did not process the request: safe to retry."""
def handle(exc):
try:
raise exc
except BankUnavailable:
return "retry later"
except ValueError as e: # InvalidAmount is a ValueError too
return f"reject: {e}"
print(handle(BankUnavailable("503 from the bank")))
print(handle(InvalidAmount("amount must be positive, got -5")))
retry later
reject: amount must be positive, got -5

The name of the class carries the decision: BankUnavailable means “try again”, InvalidAmount means “do not”. One base class (PayoutError) lets a caller catch the whole family. Put the more specific except first: Python takes the first one that matches.

A retry helps only when the next attempt can succeed. Repeating a bad request just sends it again.

FailureRetry?Why
Timeoutyes, but check firstthe request may have gone through
Connection refused before sendingyesnothing was processed
HTTP 500, 502, 503, 504yes, with pausesthe server side is temporarily broken
HTTP 429 Too Many Requestsyes, after Retry-Afteryou are over the limit
HTTP 400, 401, 403, 404, 422nothe same request fails again
Our own ValueErrornoa bug or bad input

Wait longer before each retry (exponential backoff), add randomness (jitter), and stop after a fixed number of attempts:

import random
base_delay = 0.5
delays = [base_delay * 2 ** (k - 1) for k in range(1, 6)] # before retry 1, 2, 3, ...
print(delays)
rng = random.Random(7) # seeded, so a test is repeatable
print([round(rng.uniform(0, d), 2) for d in delays]) # full jitter
[0.5, 1.0, 2.0, 4.0, 8.0]
[0.16, 0.15, 1.3, 0.29, 4.29]

Jitter spreads the retries of many clients over time, so they do not all hit a recovering server at the same moment. After the last attempt, raise your own error with the last failure as the cause: raise PayoutFailed(...) from last_error. Pass sleep in as a parameter, so tests do not wait. The full exercise, a payout where a timeout may have paid already, is in Money tasks.

TalkSay it out loud

A call to an external API sometimes fails. How do you retry it safely?

Say your answer out loud first, then open it.

Show the answer

“Retry only errors that are temporary — timeouts and 5xx, not 4xx, except 429 after Retry-After — with exponential backoff and jitter, and a limit on attempts. And the call must be idempotent: for money I send an idempotency key, so a retry after a timeout does not charge twice.”

A timeout is the hard case: the request may have reached the other side. Before you repeat a payment, ask whether it exists, using the same idempotency key.

PythonWrite a functioncore

Parse an amount string like '12.5' into Decimal with 2 decimals (half up). Surrounding spaces are allowed. Raise ValueError for empty, non-numeric or negative input, and for 'NaN' and 'Infinity'.

Data and an example

The checks run after your code and can use these:

from decimal import Decimal as D

Example: parse_amount('12.5') → D('12.50')

7 checks. Your own print() output is shown too.

from decimal import Decimal


def parse_amount(s):
    ...
Show answer

Reference

from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
CENT = Decimal("0.01")
def parse_amount(s):
if not isinstance(s, str):
raise TypeError(f"amount must be a string, got {type(s).__name__}")
try:
value = Decimal(s.strip())
except InvalidOperation as e:
raise ValueError(f"not an amount: {s!r}") from e
if not value.is_finite() or value.is_signed(): # is_signed() also catches '-0'
raise ValueError(f"bad amount: {s!r}")
try:
return value.quantize(CENT, rounding=ROUND_HALF_UP)
except InvalidOperation as e: # too many digits for cents, e.g. '1e30'
raise ValueError(f"amount too large: {s!r}") from e

Checks and the expected values

  • parse_amount('12.5') → Decimal('12.50')
  • parse_amount(' 0.125 ') → Decimal('0.13')
  • parse_amount('abc') → raises ValueError
  • parse_amount('') → raises ValueError
  • parse_amount('-1') → raises ValueError
  • parse_amount('NaN') → raises ValueError
  • parse_amount('Infinity') → raises ValueError

Decimal('abc') raises InvalidOperation. Turn it into ValueError, the error the caller expects, with from e, so the traceback shows the translation was on purpose. A value that is not a string is a wrong type, so the reference checks isinstance and raises TypeError instead of catching an AttributeError from .strip(). quantize with ROUND_HALF_UP rounds the way accountants do; round() on a Decimal rounds half to even (0.125 becomes 0.12). Decimal('NaN') is a valid Decimal too, so reject it with is_finite(), before the check for a negative value. That check is is_signed(): value < 0 lets '-0' through, and it comes out as Decimal('-0.00'). quantize can fail as well: '1e30' needs more digits than the context allows, so that call is wrapped too. The checks compare the decimal places: Decimal('12.5') does not pass for Decimal('12.50').

PythonWrite a functioncore

A payout file comes as CSV text with the header payout_id,merchant_id,amount_usd,paid_on. Read it with csv.DictReader and return (good, bad). good: the valid rows as dicts with the same four keys, amount_usd as Decimal and paid_on as date. bad: a (line_number, reason) pair for each invalid row; the header is line 1. Check in this order and report the first problem: 'missing field' (absent or empty), 'bad amount' (not a finite number), 'bad date' (not a real YYYY-MM-DD date).

Data and an example

The checks run after your code and can use these:

from datetime import date as d
from decimal import Decimal as D
CSV = """payout_id,merchant_id,amount_usd,paid_on
po_0101,mer_01,64.69,2026-09-05
po_0102,mer_02,,2026-09-05
po_0103,mer_03,n/a,2026-09-06
po_0104,mer_04,40.10,2026-09-31
po_0105,mer_05,NaN,2026-09-07
po_0106,mer_06,18.00
po_0107,mer_07,7.25,2026-09-08
"""
HEADER = CSV.splitlines()[0]

Example: parse_payouts(CSV)[0] → [{'payout_id': 'po_0101', 'merchant_id': 'mer_01', 'amount_usd': D('64.69'), 'paid_on': d(2026, 9, 5)}, {'payout_id': 'po_0107', 'merchant_id': 'mer_07', 'amount_usd': D('7.25'), 'paid_on': d(2026, 9, 8)}]

3 checks. Your own print() output is shown too.

import csv
import io
from datetime import date
from decimal import Decimal


def parse_payouts(text):
    ...
Show answer

Reference

import csv
import io
from datetime import date
from decimal import Decimal, InvalidOperation
FIELDS = ("payout_id", "merchant_id", "amount_usd", "paid_on")
def parse_payouts(text):
good, bad = [], []
reader = csv.DictReader(io.StringIO(text))
for row in reader:
line = reader.line_num # lines read so far; the header is line 1
if any(not row.get(f) for f in FIELDS): # a short row gives None, an empty field ''
bad.append((line, "missing field"))
continue
try:
amount = Decimal(row["amount_usd"])
except InvalidOperation:
amount = None
if amount is None or not amount.is_finite():
bad.append((line, "bad amount"))
continue
try:
paid_on = date.fromisoformat(row["paid_on"])
except ValueError:
bad.append((line, "bad date"))
continue
good.append({"payout_id": row["payout_id"], "merchant_id": row["merchant_id"],
"amount_usd": amount, "paid_on": paid_on})
return good, bad

Checks and the expected values

  • parse_payouts(CSV)[0] → [{'payout_id': 'po_0101', 'merchant_id': 'mer_01', 'amount_usd': Decimal('64.69'), 'paid_on': datetime.date(2026, 9, 5)}, {'payout_id': 'po_0107', 'merchant_id': 'mer_07', 'amount_usd': Decimal('7.25'), 'paid_on': datetime.date(2026, 9, 8)}]
  • parse_payouts(CSV)[1] → [(3, 'missing field'), (4, 'bad amount'), (5, 'bad date'), (6, 'bad amount'), (7, 'missing field')]
  • parse_payouts(HEADER) → ([], [])

csv.DictReader takes the header as the keys and gives each row as a dict. A short row does not fail: its missing columns come as None. So not row.get(f) catches an absent field and an empty one, and it runs first: otherwise Decimal('') on line 3 would report a bad amount. reader.line_num is the number of lines read so far, with the header as line 1. enumerate(reader, start=2) gives the same numbers here, but not when a quoted field spans two lines or a blank line is skipped. Decimal('n/a') raises InvalidOperation, while Decimal('NaN') parses, so line 6 needs is_finite(). date.fromisoformat rejects 31 September with ValueError. Collect the bad rows instead of stopping at the first one: the good rows still load, and the sender can fix the whole file at once. Ask first: “Should one bad row reject the whole file?”

PythonWrite a functioncore

parse_webhook(body) gets the JSON text of a channel webhook: {"event_id", "type", "occurred_at", "transaction": {"id", "charged_usd"}}, all values strings; occurred_at is an ISO time with Z, charged_usd a decimal string. Return a WebhookEvent (in the starter) with occurred_at as an aware datetime and charged_usd as Decimal. Raise ValueError for broken JSON, for a payload or transaction that is not an object, and for a field that is missing or invalid; the message names the field by its path, such as 'transaction.charged_usd'.

Data and an example

The checks run after your code and can use these:

from datetime import datetime as dt, timezone
from decimal import Decimal as D
OK = '{"event_id": "evt_000073", "type": "renewal", "occurred_at": "2026-08-01T01:08:33Z", "transaction": {"id": "t_007820", "charged_usd": "6.99"}}'
CUT = '{"event_id": "evt_000074", "type": "rene'
NO_TX = '{"event_id": "evt_000075", "type": "refund", "occurred_at": "2026-08-01T02:00:00Z"}'
TX_TEXT = '{"event_id": "evt_000076", "type": "renewal", "occurred_at": "2026-08-01T03:00:00Z", "transaction": "t_002200"}'
NO_AMOUNT = '{"event_id": "evt_000077", "type": "renewal", "occurred_at": "2026-08-01T04:18:35Z", "transaction": {"id": "t_002201"}}'
BAD_AMOUNT = '{"event_id": "evt_000078", "type": "renewal", "occurred_at": "2026-08-01T05:00:00Z", "transaction": {"id": "t_002202", "charged_usd": "6,99"}}'
BAD_TIME = '{"event_id": "evt_000079", "type": "purchase", "occurred_at": "2026-08-32T01:00:00Z", "transaction": {"id": "t_002203", "charged_usd": "9.99"}}'
def error(body):
"""The message of the ValueError that parse_webhook(body) raises."""
try:
parse_webhook(body)
except ValueError as e:
return str(e)
return "no ValueError"

Example: parse_webhook(OK) → WebhookEvent('evt_000073', 'renewal', dt(2026, 8, 1, 1, 8, 33, tzinfo=timezone.utc), 't_007820', D('6.99'))

8 checks. Your own print() output is shown too.

import json
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal


@dataclass(frozen=True)
class WebhookEvent:
    event_id: str
    type: str
    occurred_at: datetime
    transaction_id: str
    charged_usd: Decimal


def parse_webhook(body):
    ...
Show answer

Reference

import json
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal, InvalidOperation
@dataclass(frozen=True)
class WebhookEvent:
event_id: str
type: str
occurred_at: datetime
transaction_id: str
charged_usd: Decimal
def text(obj, key, path):
value = obj.get(key)
if not isinstance(value, str) or not value:
raise ValueError(f"{path}: missing or not a string")
return value
def parse_webhook(body):
payload = json.loads(body) # broken JSON: JSONDecodeError, a ValueError
if not isinstance(payload, dict):
raise ValueError("payload: not a JSON object")
tx = payload.get("transaction")
if not isinstance(tx, dict):
raise ValueError("transaction: missing or not an object")
raw_time = text(payload, "occurred_at", "occurred_at")
try:
occurred_at = datetime.fromisoformat(raw_time)
except ValueError as e:
raise ValueError(f"occurred_at: not an ISO time: {raw_time!r}") from e
if occurred_at.tzinfo is None:
raise ValueError(f"occurred_at: no time zone: {raw_time!r}")
raw_amount = text(tx, "charged_usd", "transaction.charged_usd")
try:
charged = Decimal(raw_amount)
except InvalidOperation as e:
raise ValueError(f"transaction.charged_usd: not an amount: {raw_amount!r}") from e
if not charged.is_finite():
raise ValueError(f"transaction.charged_usd: not an amount: {raw_amount!r}")
return WebhookEvent(
event_id=text(payload, "event_id", "event_id"),
type=text(payload, "type", "type"),
occurred_at=occurred_at,
transaction_id=text(tx, "id", "transaction.id"),
charged_usd=charged,
)

Checks and the expected values

  • parse_webhook(OK) → WebhookEvent(event_id='evt_000073', type='renewal', occurred_at=datetime.datetime(2026, 8, 1, 1, 8, 33, tzinfo=datetime.timezone.utc), transaction_id='t_007820', charged_usd=Decimal('6.99'))
  • parse_webhook(CUT) → raises JSONDecodeError
  • parse_webhook('[]') → raises ValueError
  • 'transaction' in error(NO_TX) → True
  • 'transaction' in error(TX_TEXT) → True
  • 'transaction.charged_usd' in error(NO_AMOUNT) → True
  • 'transaction.charged_usd' in error(BAD_AMOUNT) → True
  • 'occurred_at' in error(BAD_TIME) → True

json.loads raises json.JSONDecodeError for broken JSON. It is a subclass of ValueError, so the second check needs no extra code. Valid JSON can still have the wrong shape: a list instead of an object, or a string where transaction should be an object. Check with isinstance(..., dict) before you index, and read the fields with .get(): payload["transaction"] raises KeyError and "t_002200"["id"] raises TypeError, and neither says which field is wrong. The error from fromisoformat names the day and the month, but not the field, so catch it and raise a ValueError that names occurred_at, with from e. The amount arrives as a string and goes straight into Decimal; a JSON number would already be a float, and json.loads(body, parse_float=Decimal) avoids that. The frozen dataclass is the record that the rest of the code can trust.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.