RAISE · TRACEBACK · EXCEPT · FINALLY · YOUR ERRORS · CHAINING · BOUNDARY · RETRIES · GROUPS

Exceptions in Python:
how errors travel and where to catch them

An exception is how Python reports that a line could not do its job. It stops that function and climbs back through every caller until code that expects it catches it. You decide where it is caught, what gets cleaned up on the way, and what the person or program that started your code finally sees.

A small online tea shop sells through three partner marketplaces. Every night a Python job downloads each partner’s orders, checks every record, saves the new orders to the shop’s database and logs a summary. Tonight one record has a quantity of “2 pcs”, one partner is down for maintenance and another rejects the shop’s expired key. Each chapter runs tonight’s import again with one more piece of error handling in place, starting with a job that stops at the first bad record.

Here is the job’s error handling, complete. Most chips won’t mean much yet; each chapter explains one of them.

MapEach box is a function of the job, callers above callees. Arrows point the way an error climbs; chips sit on the function that owns them.

You need to know Python functions, classes, imports and with open(…); no study of exceptions is assumed. The tutorial teaches Python 3.15, checked against its source and documentation on 28 November 2026; samples use only the standard library. The tea shop, its partners and tonight’s numbers are made up; every message, default and format comes from Python itself. Tap any figure to open it full screen and zoom. Dotted terms are tappable.

When a line fails: the exception and the climb

Tonight’s import reads harbor’s orders one record at a time and turns each quantity into a number with int(). Record 118 says its quantity is “2 pcs”, and int() can’t turn that into a number. It can’t return a wrong number either, because every caller would trust it. Instead it raises an exception: it stops, and hands the problem back to whoever called it. What happens, frame by frame, when one line of Python fails?

STEP 01 / 04

THE MAP SO FAR

Fig 1.1The accent parts are new: the raise, the object it creates, the climb and the default handler. Faint parts arrive later.

The job is five functions that call each other, drawn callers above callees, all in one Python process. While a function runs, Python keeps a frame for it: its local variables and the line it is on. The frames of every call that hasn’t returned yet form the call stack, here from main() at the top down to int() at the bottom.

Four parts are new in this chapter. The raise inside int() stops the line that failed. The exception object it creates carries the error’s type and message. The accent arrows are the climb from callee to caller, and above main() sits Python’s default handler, which reports any error nothing else caught. Everything drawn faint arrives in a later chapter.

STEP 02 / 04

AN EXCEPTION IS AN OBJECT, AND RAISE THROWS IT

Fig 1.2The accent box is what raise hands up the stack: a type and a message.

int("2 pcs") can’t produce a number, so it creates an exception: an object of class ValueError, whose args hold one message, invalid literal for int() with base 10: '2 pcs'. str(err) returns the same text. Then int() raises the object, and parse_order gets that object instead of a return value.

Your own code raises the same way: line 17 of records.py below raises a ValueError of its own when a quantity is below 1. The raise statement takes an exception instance or a class. Given a class, as in raise ValueError, Python creates the instance with no arguments. Either way the line stops there, and the next line of that function doesn’t run.

RECORDS.PY: LINE 15 FAILS TONIGHT, LINE 17 IS YOUR OWN RAISE
"""Turn one partner record into an Order."""
from dataclasses import dataclass
from decimal import Decimal


@dataclass(frozen=True)
class Order:
    id: str
    sku: str
    qty: int
    price: Decimal


def parse_order(record: dict[str, str], partner: str, n: int) -> Order:
    qty = int(record["qty"])
    if qty < 1:
        raise ValueError(f"qty must be at least 1, got {qty}")  # your own raise
    return Order(record["id"], record["sku"], qty, Decimal(record["price"]))
STEP 03 / 04

THE ERROR CLIMBS FROM CALLEE TO CALLER

Fig 1.3Follow 1 to 5. Beside each frame is the line it never reached.

Nothing in tonight’s job catches the ValueError, so Python ends the frames one at a time, from callee to caller. This is unwinding. parse_order never assigns qty. import_partner never saves record 118 and never reads records 119 to 214. run_import never reaches meadow or north, and main() ends too.

A frame that ends this way returns no value to its caller. The error appears at the caller’s line instead, the one that made the call, and the climb goes on from there. The rest of each frame is skipped, including lines that would tidy up: run_import never reaches conn.commit() or conn.close().

STEP 04 / 04

NOTHING CATCHES IT, SO PYTHON PRINTS AND EXITS 1

Fig 1.4The accent legs leave the process: the traceback goes to stderr, the status to whoever started it.

Past main() the error reaches Python’s default handler, sys.excepthook. It prints the traceback to stderr, the error stream, and the process ends with exit status 1. Whoever started the job reads that number: 0 means success, and anything else is a failure.

stdout gets nothing, so a script that pipes the job’s normal output sees an empty stream. cron mails whatever the job printed to the crontab’s owner when the machine can send mail, and drops it otherwise. Chapter 07 decides what the top of the program does instead.

TONIGHT’S RUN: STATUS 1, A TRACEBACK ON STDERR
python -m orderfeed --date 2026-11-27 2> stderr.txt
echo $?
# 1
head -n 1 stderr.txt
# Traceback (most recent call last):

COMMON QUESTIONS

Is an exception always an error?
No. StopIteration is how an iterator tells a for loop it has run out, and SystemExit is how sys.exit() ends a program. An exception is a way to leave several frames at once; most of them report errors.
Does a try block slow my code down?
Not while nothing is raised. Since Python 3.11, entering a try block costs nothing; the cost comes only when an exception is actually raised and caught.
Can I raise a string?
No. raise takes an exception class or an instance of one. Anything else raises TypeError: exceptions must derive from BaseException.

WHAT YOU NOW KNOW

  • int("2 pcs") creates a ValueError object holding its message and raises it, which stops that line.
  • With no handler, the error ends parse_order, import_partner, run_import and main in turn, skipping the rest of each.
  • Python’s default handler then prints the traceback to stderr, and the process exits with status 1.
DEEP DIVE: what raise accepts, BaseException and its attributes, the cost of raising, signals and KeyboardInterrupt

What raise accepts

raise takes an exception class or an instance of one: anything that derives from BaseException. raise ValueError calls the class with no arguments and raises the result. Anything else, such as a string, raises TypeError: exceptions must derive from BaseException in its place.

A bare raise, with nothing after it, raises again the exception currently being handled; chapter 03’s deep dive uses it. With no exception being handled it raises RuntimeError: No active exception to reraise.

BaseException and its attributes

args is the tuple of arguments the exception was created with. str(err) returns the single argument when there is one, the tuple’s text when there are several, and an empty string when there are none. KeyError is the exception to the rule: it prints the repr of its key, so a missing key reads KeyError: 'qty', quotes included.

err.with_traceback(tb) replaces the exception’s traceback and returns the exception, so it can be raised in one line. Chapter 02 shows what that traceback holds.

The cost of raising

Since Python 3.11 a try block costs nothing on the way in. The compiler writes a table of protected ranges beside the bytecode, which replaced the setup instruction older versions ran on entry. Raising does cost time: Python builds the exception object and adds a traceback entry for every frame it leaves.

So exceptions suit events that are rare compared with the work around them, such as a bad record in a batch of hundreds. Python’s own iteration uses one: an iterator raises StopIteration when it runs out, and the for loop stops there.

Signals and KeyboardInterrupt

Ctrl-C sends SIGINT to the process. Python’s C-level signal handler only sets a flag, and the interpreter checks it between bytecode instructions, so KeyboardInterrupt is raised in whatever line runs next, even in the middle of a loop that has nothing to do with input.

If nothing catches it, Python resets SIGINT to its default action and sends the signal to itself. The shell then sees a process killed by SIGINT and reports 130, which is 128 plus SIGINT’s number, 2. On Windows the status is STATUS_CONTROL_C_EXIT.

ERRORS THIS CHAPTER EXPLAINS

TypeError: exceptions must derive from BaseException
a raise of a string, or of another object that isn’t an exception
raise an exception class or instance, such as ValueError("…")
RuntimeError: No active exception to reraise
a bare raise with no exception being handled
raise a specific exception instead

Reading the climb back: the traceback

The import stopped, and stderr holds a block of text that starts with Traceback (most recent call last):. It looks like noise, but it is a precise record of the climb from chapter 01: every frame the error left, each with its file, line number and source line, and at the bottom the error’s type and message. Reading it in the right order takes seconds. How do you find the line that failed, and how the program got there?

STEP 01 / 04

THE MAP SO FAR

Fig 2.1The accent parts are new: the traceback on stderr and the record it is printed from.

The traceback is the text Python’s default handler prints on stderr when an error reaches the top: one entry for every frame the error left, oldest call first, then the error itself. It is printed from the exception object, which collects one entry per frame as it climbs.

Two parts are new on the map. The accent line from the default handler to cron is the traceback on stderr. In the in-memory band, __traceback__ is the record on the exception object that the text is printed from.

STEP 02 / 04

A TRACEBACK LISTS THE CALLS OLDEST FIRST

Fig 2.2Each traceback entry sits beside the frame it came from. The accent entry is the line that failed.

“Most recent call last” means the entries are in call order. The first two come from <frozen runpy>, the code behind python -m, and are the same in every program. Then come __main__.py, main, run_import, import_partner and parse_order, each a File line naming the file, line number and function, followed by that line’s source.

The last entry is the line that failed: records.py, line 15, qty = int(record["qty"]). The very last line is the error’s type and message. So read a traceback from the bottom up: what failed, then where, then who called it.

TONIGHT’S TRACEBACK ON STDERR
Traceback (most recent call last):
  File "<frozen runpy>", line 201, in _run_module_as_main
  File "<frozen runpy>", line 87, in _run_code
  File "/srv/orderfeed/src/orderfeed/__main__.py", line 3, in <module>
    main()
    ~~~~^^
  File "/srv/orderfeed/src/orderfeed/cli.py", line 15, in main
    run_import(PARTNERS, args.db, args.date)
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/orderfeed/src/orderfeed/job.py", line 24, in run_import
    saved = import_partner(partner, conn, day)
  File "/srv/orderfeed/src/orderfeed/job.py", line 15, in import_partner
    order = parse_order(record, partner.name, n)
  File "/srv/orderfeed/src/orderfeed/records.py", line 15, in parse_order
    qty = int(record["qty"])
ValueError: invalid literal for int() with base 10: '2 pcs'
STEP 03 / 04

CARETS MARK THE PART OF THE LINE THAT FAILED

Fig 2.3Two ways the line can fail. The accent part is the one the carets point at.

Since Python 3.11 a traceback can underline the part of a line that raised, with a caret line. If the record had no "qty" key, line 15 would get ~~~~~~^^^^^^^ under record["qty"]: ~ under the value being subscripted, ^ under the subscript that raised. The message would be KeyError: 'qty', the missing key with its quotes.

Tonight’s line prints no caret line. When a line assigns the result of one call, as qty = int(…) does, the call is the whole right-hand side and the source line already says what raised. A call standing alone on its line isn’t exempt, which is why tonight’s traceback underlines main() and run_import(…).

In a terminal the traceback is in colour. PYTHON_COLORS=0 turns that off, and output to a file or a pipe, as under cron, is plain text.

THE SAME LINE IF THE RECORD HAD NO QTY KEY
Traceback (most recent call last):
  File "<frozen runpy>", line 201, in _run_module_as_main
  File "<frozen runpy>", line 87, in _run_code
  File "/srv/orderfeed/src/orderfeed/__main__.py", line 3, in <module>
    main()
    ~~~~^^
  File "/srv/orderfeed/src/orderfeed/cli.py", line 15, in main
    run_import(PARTNERS, args.db, args.date)
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/srv/orderfeed/src/orderfeed/job.py", line 24, in run_import
    saved = import_partner(partner, conn, day)
  File "/srv/orderfeed/src/orderfeed/job.py", line 15, in import_partner
    order = parse_order(record, partner.name, n)
  File "/srv/orderfeed/src/orderfeed/records.py", line 15, in parse_order
    qty = int(record["qty"])
              ~~~~~~^^^^^^^
KeyError: 'qty'
STEP 04 / 04

THE TRACEBACK TRAVELS WITH THE EXCEPTION

Fig 2.4The accent arrows are the traceback’s links, newest entry last. Each one keeps a whole frame alive.

The exception keeps its traceback in err.__traceback__: a linked list with one entry per frame the error left. Each entry holds its frame in tb_frame, the line number in tb_lineno and the next entry in tb_next. traceback.format_exception(err) turns the list into the same text stderr showed, at any time; chapter 07’s logging does exactly that.

Each entry keeps its frame, and a frame keeps every local variable, so a stored exception keeps all of them alive. That is why Python deletes the as err name when an except block ends, and the sample’s last line fails with NameError. The sample catches the error with try and except, which chapter 03 explains; here they only hand you the object.

THE TRACEBACK AS DATA, AND THE NAME PYTHON DELETES
import traceback

from orderfeed.records import parse_order

record = {"id": "H-20931", "sku": "ASSAM-100G", "qty": "2 pcs", "price": "7.50"}
try:
    parse_order(record, "harbor", 118)
except ValueError as err:
    text = "".join(traceback.format_exception(err))  # the text stderr would show
    last = traceback.extract_tb(err.__traceback__)[-1]
    print(last.name, last.lineno)                     # int is built in, so: parse_order 15
print(err)  # NameError: name 'err' is not defined (deleted when the block ended)

COMMON QUESTIONS

Why does the traceback start with <frozen runpy>?
That is the code behind python -m, which finds and runs your package. Those two entries are the same in every program started this way, so skip them.
Why is the error on the last line, not the first?
Python prints the calls in the order they were made, oldest first, so the line that failed comes last, next to the message. In a terminal that keeps the most useful lines on screen.
Can I get a traceback without crashing?
Yes. Inside an except block, traceback.print_exc() prints the current one and the program carries on. logger.exception() writes it to a log instead, as chapter 07 does.

WHAT YOU NOW KNOW

  • Tonight’s traceback reads bottom up: ValueError for '2 pcs', raised at records.py line 15, called from import_partner.
  • Carets underline the part that raised, such as record["qty"], and are left out when one call is the whole right-hand side.
  • err.__traceback__ keeps one entry per frame the error left, so the same text can be printed or logged later.
DEEP DIVE: “Did you mean” hints, long and recursive tracebacks, colour and plain text, faulthandler

“Did you mean” hints

When a name or attribute is misspelled, the message ends with a suggestion: NameError: name 'qyt' is not defined. Did you mean: 'qty'?. Python 3.10 added these for names and attributes, 3.12 added Did you forget to import 'sys'?, 3.13 covered keyword arguments and 3.14 misspelled keywords.

Python 3.15 also suggests attributes of nested objects and methods from other languages: 'list' object has no attribute 'push'. Did you mean '.append'?

Long and recursive tracebacks

A function that calls itself with no stop condition fails with RecursionError: maximum recursion depth exceeded once the stack reaches Python’s default limit of 1000 frames. Printing every identical entry would bury the message, so the traceback shows the repeated entry three times, then [Previous line repeated 996 more times].

traceback.print_exception(err, limit=5) prints only the first five entries of any traceback; a negative limit keeps the last ones instead.

Colour and plain text

Python decides on colour from the environment, in this order: PYTHON_COLORS (0 or 1) wins, then NO_COLOR, then FORCE_COLOR, then TERM=dumb, and last whether stderr is a terminal. Cron, a pipe and a log file get plain text.

-X no_debug_ranges, or PYTHONNODEBUGRANGES, drops the caret lines along with the column positions behind them, which saves a little memory and disk.

faulthandler

Some crashes raise no Python exception at all: a segmentation fault in a C extension ends the process with no traceback. python -X faulthandler, or PYTHONFAULTHANDLER=1, installs a handler that dumps every thread’s Python stack to stderr when that happens, so you still learn which line was running.

ERRORS THIS CHAPTER EXPLAINS

RecursionError: maximum recursion depth exceeded
a function that calls itself with no end
find the repeated entry and check its stop condition
NameError: name 'qyt' is not defined. Did you mean: 'qty'?
a typo in a name
the hint names the fix

Catching by class: try, except and the hierarchy

One bad quantity stopped the whole import. Harbor’s records after 118 were never read, and meadow and north were never tried. The record is wrong and the job is fine, so the right move is to skip that record, count it and carry on. That needs a frame that expects the error and says what to do with it. Which except clause catches an error, and how do you catch only what you can handle?

STEP 01 / 05

THE MAP SO FAR

Fig 3.1The accent parts are new: the handler on import_partner and the classes it matches against.

Two parts are new. In import_partner, a try statement now wraps the parsing of each record, and its except clause skips a record that fails and counts it. That clause is a handler: code that catches an exception and decides what happens next. Here the frame carries on with the next record.

The second new part is the tree of built-in exception classes, at the bottom of the map. It decides which errors the clause catches. Everything faint arrives in a later chapter.

STEP 02 / 05

EXCEPT MATCHES BY CLASS, TOP TO BOTTOM

Fig 3.2The clauses as Python tries them. The accent row matched; the row below it was never reached.

When the try body raises, Python compares the exception with each except clause in order and runs the first one that matches. The test is isinstance(err, cls), so a clause for a class also matches every subclass of it. The clauses after the match are skipped, and the frame continues on the first line after the whole try statement.

In the sample, record 118 makes int() raise ValueError. except KeyError doesn’t match, except ValueError does, and except Exception is never reached. One clause can name several classes as a tuple, except (KeyError, ValueError) as err:. Since Python 3.14 the parentheses can go when there is no as: except KeyError, ValueError:.

THREE CLAUSES, TRIED IN ORDER
from orderfeed.records import parse_order

record = {"id": "H-20931", "sku": "ASSAM-100G", "qty": "2 pcs", "price": "7.50"}
try:
    order = parse_order(record, "harbor", 118)
except KeyError as err:        # not a KeyError: skipped
    print("missing field:", err)
except ValueError as err:      # matches: this block runs
    print("bad value:", err)
except Exception:              # never reached for this error
    print("something else went wrong")
print("carries on here")       # runs after the handler
STEP 03 / 05

THE HIERARCHY DECIDES WHAT A CLAUSE CATCHES

Fig 3.3A clause catches its own class and every class under it. The accent line marks what except Exception leaves alone.

Exception classes form a tree, the exception hierarchy, and a clause catches its class and every class under it. except ValueError also catches json.JSONDecodeError and UnicodeDecodeError. except OSError catches TimeoutError, ConnectionResetError and urllib’s URLError. except LookupError catches both KeyError and IndexError.

The root is BaseException. Under it, Exception is the parent of every error. Beside it sit KeyboardInterrupt (Ctrl-C), SystemExit (sys.exit()), GeneratorExit and asyncio’s CancelledError. Those four aren’t errors: they tell a program or a task to stop. That is why the widest clause you should write, except Exception, lets them pass.

STEP 04 / 05

CATCH ONLY WHAT YOU CAN HANDLE, IN THE SMALLEST TRY

Fig 3.4The same typo under two handlers. The accent column lets it crash; the other reports success.

Compare two versions of the loop. The wide one puts try around parsing and saving and catches Exception. Now add a typo to save_order: order.prce for order.price. Every record raises AttributeError, the handler counts each one as skipped, and the run ends with 214 of 214 records skipped, nothing saved and exit status 0.

The narrow version below guards only the parse_order call and names the two classes bad data raises: KeyError for a missing field, ValueError for a bad value. Record 118 is skipped with a warning. The typo raises AttributeError on record 1, outside the try, and the job stops with a traceback that points at the line.

IMPORT_PARTNER: A SMALL TRY AROUND PARSE_ORDER
def import_partner(partner: Partner, conn: sqlite3.Connection, day: str) -> int:
    saved = skipped = 0
    for n, record in enumerate(fetch_orders(partner, day), start=1):
        try:
            order = parse_order(record, partner.name, n)  # the only guarded line
        except (KeyError, ValueError) as err:
            skipped += 1
            log.warning("%s record %d skipped: %s", partner.name, n, err)
            continue
        save_order(conn, order)                           # a bug here still crashes
        saved += 1
    log.info("%s: %d saved, %d skipped", partner.name, saved, skipped)
    return saved
STEP 05 / 05

IN PYTHON, TRY FIRST AND HANDLE THE FAILURE

Fig 3.5The accent gap is where the file can vanish. The try version has no gap.

An operation that might fail can be handled two ways. Look before you leap, LBYL, checks first: if os.path.exists(path):. Easier to ask forgiveness than permission, EAFP, tries the operation and catches its failure: open(path) inside try, with except FileNotFoundError:.

Python code prefers EAFP wherever a check can go stale. Between os.path.exists() and open() another process can delete the file, and open() then raises anyway. The try version is one step, so there is no gap. For a dictionary key either style is fine, and record.get("qty") is often the simplest.

LOOK FIRST, OR TRY IT
import json
import os

path = "cache/harbor.json"

# Look first: the file can vanish between the check and the open.
if os.path.exists(path):
    with open(path) as f:
        records = json.load(f)

# Try it: one step, so there is no gap to fall into.
try:
    with open(path) as f:
        records = json.load(f)
except FileNotFoundError:
    records = []

COMMON QUESTIONS

Should I ever write except Exception?
Yes, at the very top of a program or a unit of work, where any error means “log it and stop this piece”. Inside your logic, name the classes you expect.
What is the as err for?
It names the exception object inside the block, so you can read its message or fields. Python deletes the name when the block ends.
Can one clause catch several classes?
Yes: except (KeyError, ValueError) as err:. Python 3.14 and later also accept the classes without parentheses when you don’t use as.

WHAT YOU NOW KNOW

  • except clauses are tried top to bottom, and the first whose class is the error’s class, or a parent of it, runs.
  • except ValueError also catches JSONDecodeError, and except Exception leaves Ctrl-C and sys.exit() alone.
  • A small try around parse_order skips record 118 and still lets a typo in save_order crash where you see it.
DEEP DIVE: re-raising, catching what a library raises, contextlib.suppress, warnings are not exceptions

Re-raising

Inside a handler, a bare raise sends the same exception on up the stack with its traceback unchanged. Use it when the frame can do part of the job, such as logging or cleaning up, but can’t finish it. raise err also re-raises it, and adds the line of the raise to the traceback. Both keep the error climbing; neither changes its class.

Catching what a library raises

A library’s documentation lists the classes it raises, and those are the ones to name. urllib raises URLError when it can’t connect and HTTPError, a subclass of it, for an error status. A server that accepts the connection and then stalls gives a bare TimeoutError instead, so a download needs except (URLError, TimeoutError).

Check the tree before trusting a name. Decimal("7,50") raises decimal.InvalidOperation, an ArithmeticError, not a ValueError. A price with a comma would get past except (KeyError, ValueError) and stop the job, until the tuple names InvalidOperation too.

contextlib.suppress

with suppress(FileNotFoundError): is try with an except FileNotFoundError: pass, written for “this may fail, and that is fine”. It reads well around one line. Around several, the lines after the one that raised are skipped too, which is easy to miss.

AN ERROR THAT DOESN’T MATTER
import os
from contextlib import suppress

with suppress(FileNotFoundError):    # already gone is fine
    os.remove("cache/harbor.json")

Warnings are not exceptions

warnings.warn() reports a problem and lets the line carry on. By default Python shows a DeprecationWarning only when code in __main__ triggers it, so library deprecations stay hidden in a normal run. Running the tests with -W error turns every warning into an exception, which makes them impossible to miss in CI. Python 3.13 added @warnings.deprecated to mark a function as deprecated.

ERRORS THIS CHAPTER EXPLAINS

UnboundLocalError: cannot access local variable 'order' where it is not associated with a value
the try failed before it assigned order, and code after the except used the name
end the handler with continue, return or raise, so nothing after it runs without a value
SyntaxError: multiple exception types must be parenthesized when using 'as'
except KeyError, ValueError as err:
put the classes in parentheses; only the form without as may leave them out
a run that exits 0 with every record skipped
a handler too broad, catching a bug as if it were bad data
narrow the classes and the try, then run it again to see the real error

Cleanup that always runs: else, finally and with

Record 118 is skipped now, and the import gets further. At record 170, harbor sends order H-20877 a second time (it first came as record 41), and the database refuses it with sqlite3.IntegrityError: UNIQUE constraint failed: orders.id. The error climbs past conn.commit() and conn.close(), the last two lines of run_import, so neither runs. The 168 orders inserted before it sit in a transaction that nobody commits or rolls back. How do you close a connection or undo a transaction, whatever happened?

STEP 01 / 04

THE MAP SO FAR

Fig 4.1The accent chip is new: cleanup attached to the frame that opened the connection.

One part is new: the with statements in run_import. One closes the database connection. The other wraps each partner’s inserts in a transaction: a group of database changes that a commit saves together, or that are undone together.

Both run their cleanup while an error climbs through run_import. The frame that opened the connection is the one that ends it, whatever happens in the frames below. Everything faint arrives in a later chapter.

STEP 02 / 04

FOUR BLOCKS, AND WHICH ONES RUN

Fig 4.2One row per way the try can end. The accent column runs in every row.

A try statement can have four blocks. try runs until something in it raises. except runs only for an error its class matches. else runs only if try finished without raising. It holds code that should run on success, kept out of try so that its own errors aren’t caught by the clauses above it.

finally runs on every way out: no error, an error caught, an error no clause caught, and a return inside try. In the sample, finally logs how long harbor took whether the download worked or not. The except logs a warning and then re-raises with a bare raise, so the caller still sees the error.

TRY, EXCEPT, ELSE AND FINALLY AROUND THE DOWNLOAD
def import_partner(partner: Partner, conn: sqlite3.Connection, day: str) -> int:
    started = time.monotonic()
    try:
        records = fetch_orders(partner, day)
    except OSError:
        log.warning("%s: download failed", partner.name)
        raise                                    # still an error for the caller
    else:
        return save_all(conn, partner, records)  # only if the download worked
    finally:
        log.info("%s took %.1f s", partner.name, time.monotonic() - started)
STEP 03 / 04

WITH RUNS THE CLEANUP FOR YOU

Fig 4.3Follow the error path: __exit__ runs, returns nothing true, and the error climbs on.

A with statement is a try and finally that come with the object. Python calls the object’s __enter__ method before the block and its __exit__ method on the way out, passing the exception if one is climbing. An object built for this is a context manager. When __exit__ returns a false value, as almost all do, the error keeps climbing after the cleanup.

with open(path) as f: closes the file. A sqlite3 connection needs closing() from contextlib: with closing(sqlite3.connect(db, autocommit=False)) as conn: calls conn.close() on the way out. To write a context manager of your own, read the context-manager chapter of the behavioral patterns tutorial.

TWO WITH STATEMENTS, AND THE FIRST WRITTEN OUT
import sqlite3
from contextlib import closing

with open("cache/harbor.json") as f:   # f.close() on the way out
    data = f.read()

with closing(sqlite3.connect("orders.db", autocommit=False)) as conn:
    conn.execute("SELECT 1")                 # conn.close() on the way out

# The first with, written out by hand:
f = open("cache/harbor.json")
try:
    data = f.read()
finally:
    f.close()
STEP 04 / 04

THE CONNECTION’S WITH COMMITS OR ROLLS BACK, NOT CLOSES

Fig 4.4Follow the error from record 170: the transaction rolls back, then the connection closes, then the error climbs on.

with conn: on a sqlite3 connection is a transaction. It commits if the block finishes and rolls back if the block raises. It does not close the connection; closing() does. run_import below nests the two: closing() once around the whole run, and with conn: once per partner.

So record 170 raises IntegrityError inside harbor’s with conn:. Its exit rolls back all 168 inserts, closing() closes the connection, and the error climbs on to main(). The repeat itself is fixed in the SQL: ON CONFLICT(id) DO NOTHING turns record 170 into an insert that does nothing. Harbor then commits 212 orders, and running the job again is safe.

RUN_IMPORT: ONE TRANSACTION PER PARTNER
INSERT = """
    INSERT INTO orders (id, sku, qty, price) VALUES (?, ?, ?, ?)
    ON CONFLICT(id) DO NOTHING
"""


def run_import(partners: list[Partner], db_path: str, day: str) -> None:
    with closing(sqlite3.connect(db_path, autocommit=False)) as conn:  # closes it
        for partner in partners:
            with conn:   # commits this partner, or rolls all of it back
                saved = import_partner(partner, conn, day)
            log.info("%s: %d saved", partner.name, saved)

COMMON QUESTIONS

When do I need else?
When code should run only after the try succeeded, and its own errors must not be caught by the except above it. Saving what the try fetched is the usual case.
Does finally run on Ctrl-C?
Yes. KeyboardInterrupt climbs through finally blocks and with exits like any exception. Nothing runs if the process is killed with kill -9.
Should a duplicate stop the import?
Not here: the order already exists. ON CONFLICT DO NOTHING makes saving it a second time harmless, which also makes re-running the whole job safe.

WHAT YOU NOW KNOW

  • finally runs on every way out of a try, so cleanup there survives the IntegrityError at record 170.
  • with closing(connect(…)) closes the connection; with conn: commits harbor’s batch or rolls all 168 inserts back.
  • ON CONFLICT(id) DO NOTHING makes the repeated order harmless, so harbor commits 212 orders and a re-run is safe.
DEEP DIVE: ExitStack for many resources, an error inside cleanup, generators and GeneratorExit, autocommit modes

ExitStack for many resources

When the number of resources is known only at run time, such as one cache file per partner, nested with statements can’t be written out. contextlib.ExitStack collects them: enter_context() enters each one and keeps its exit, and callback() adds any function. When the block ends, the exits run in reverse order. If opening the third file fails, the first two are still closed.

ONE CACHE FILE PER PARTNER, ALL CLOSED
from contextlib import ExitStack

names = ["harbor", "meadow", "north"]
with ExitStack() as stack:
    files = [stack.enter_context(open(f"cache/{name}.json")) for name in names]
    stack.callback(log.info, "cache files closed")
    for f in files:
        print(f.readline())   # if this raises, every file is still closed

An error inside cleanup

If finally or __exit__ raises, the new exception replaces the one that was climbing. The original is not lost: Python attaches it to the new one and prints it first, followed by During handling of the above exception, another exception occurred:. The traceback then ends with the cleanup’s failure instead of the real one, so keep cleanup code short and unlikely to fail.

Generators and GeneratorExit

A generator paused at yield can be inside a with or try block. Calling its close(), or dropping the last reference to it, raises GeneratorExit at that yield, so the cleanup runs. A generator may catch it to clean up, but it must not yield again: that raises RuntimeError: generator ignored GeneratorExit.

autocommit modes

sqlite3.connect has three transaction modes, set with autocommit=. LEGACY_TRANSACTION_CONTROL is still the default in 3.15 and opens a transaction only before INSERT, UPDATE, DELETE or REPLACE; the docs say the default will change to False in a future release.

False, which the docs recommend and the samples use, keeps a transaction open at all times: commit() and rollback() end one and start the next. True lets SQLite commit each statement on its own, and with conn: then does nothing.

ERRORS THIS CHAPTER EXPLAINS

sqlite3.IntegrityError: UNIQUE constraint failed: orders.id
the row’s key is already in the table
ON CONFLICT(id) DO NOTHING when a repeat is harmless; otherwise find out why the source repeats it
sqlite3.ProgrammingError: Cannot operate on a closed database.
the connection was used after closing() closed it
keep the work inside the with block
SyntaxWarning: 'return' in a 'finally' block
a return that would throw away the error climbing through the finally
move the return after the try statement

Errors your callers can act on: your own classes

Harbor imports cleanly now: 212 orders saved. Then meadow answers 503 Service Unavailable, and urllib raises HTTPError. Up in main, that error looks exactly like north’s rejected key, an HTTPError with status 401, and nothing like a bad record. Yet each needs something different: try meadow again later, have a person renew north’s key, skip the record. Callers need errors named after what they should do. When should you define your own exception, and how should the classes be arranged?

STEP 01 / 04

THE MAP SO FAR

Fig 5.1The accent node is new: the job’s own exception classes, beside the built-in ones. Faint parts arrive later.

So far every error in the job is a built-in class: ValueError from int(), IntegrityError from sqlite3, HTTPError from urllib. This chapter adds the job’s own exception classes, in a new module, errors.py. On the map they sit in the in-memory band beside the built-in classes, because a class is what an except clause matches against.

The job’s code raises them, and callers catch them by name. Each class names a failure in the job’s own terms (a bad record, a partner that is down, a rejected key) instead of naming the library that noticed it.

STEP 02 / 04

RAISE WHEN A FUNCTION CAN’T DO ITS JOB

Fig 5.2The same bad record, two ways. The accent column fails where the problem is.

An earlier draft of parse_order caught the error itself and returned None for a bad record. One caller, order_total, forgot to check. For record 118 the None travelled on, and the failure came later, in that caller: AttributeError: 'NoneType' object has no attribute 'qty'. The message names neither the record nor the field.

Raising stops at the cause. parse_order raises an error that names record 118, and no caller can use a result by accident, because there is none. Return None only when “nothing” is a normal answer, as dict.get does for a missing key.

A DRAFT THAT RETURNS NONE, AND A CALLER THAT FORGETS TO CHECK
def parse_order(record: dict[str, str], partner: str, n: int) -> Order | None:
    try:
        qty = int(record["qty"])
    except (KeyError, ValueError):
        return None                   # the failure becomes a value
    return Order(record["id"], record["sku"], qty, Decimal(record["price"]))


def order_total(record: dict[str, str], partner: str, n: int) -> Decimal:
    order = parse_order(record, partner, n)  # None for record 118; nobody checks
    return order.qty * order.price
    # AttributeError: 'NoneType' object has no attribute 'qty'
STEP 03 / 04

ONE BASE CLASS, ONE SUBCLASS PER THING A CALLER DOES

Fig 5.3Each subclass carries the action its callers take. The accent row is the one the job’s design rests on.

errors.py defines OrderFeedError, a subclass of Exception, as the job’s base class, so one clause, except OrderFeedError, catches everything the job raises on purpose. Under it sits one class per action a caller takes: InvalidRecordError (skip the record), PartnerUnavailableError (try again later) and PartnerAuthError (a person must fix the key).

PEP 8, Python’s style guide, gives the naming rules: derive exceptions from Exception, and end the name in Error when the exception is an error. Make a new class only when a caller would do something different. Ten messages that all mean “skip this record” are one class with ten messages.

ERRORS.PY: ONE CLASS PER THING A CALLER DOES NEXT
"""The job's own exceptions: one class per thing a caller does next."""


class OrderFeedError(Exception):
    """Base class: catch this to catch everything orderfeed raises on purpose."""


class InvalidRecordError(OrderFeedError):
    """One record is wrong. Skip it, count it, keep importing."""


class PartnerUnavailableError(OrderFeedError):
    """A partner could not be reached or is down. Try again later."""


class PartnerAuthError(OrderFeedError):
    """A partner rejected the API key. A person must fix the configuration."""
STEP 04 / 04

GIVE THE EXCEPTION THE FIELDS A HANDLER NEEDS

Fig 5.4The accent rows are fields the handler reads. The message in args is for people.

InvalidRecordError takes four keyword-only arguments: partner, n, field and value. Its __init__ builds the message from them, passes only the message to super().__init__, and keeps each one as an attribute. A handler can count skipped records by err.partner, or report err.n, without parsing text.

str(err) stays a readable sentence, harbor record 118: qty '2 pcs' is not valid, and that is what the log line shows. The fields serve code, the message serves people, and neither has to be squeezed into the other.

FIELDS FOR THE HANDLER, A SENTENCE FOR PEOPLE
class InvalidRecordError(OrderFeedError):
    """One record is wrong. Skip it, count it, keep importing."""

    def __init__(self, *, partner: str, n: int, field: str, value: str) -> None:
        super().__init__(f"{partner} record {n}: {field} {value!r} is not valid")
        self.partner = partner
        self.n = n
        self.field = field
        self.value = value


err = InvalidRecordError(partner="harbor", n=118, field="qty", value="2 pcs")
print(err)    # harbor record 118: qty '2 pcs' is not valid
print(err.n)  # 118

COMMON QUESTIONS

Should every module have its own exceptions?
No. One base class for the package and a few subclasses is usually enough. For wrong arguments to a function, reuse ValueError and TypeError, which every caller already knows.
Is assert a way to raise errors?
No. python -O removes every assert, so assert suits checks of your own assumptions, never the validation of input.
Can my class also be a ValueError?
Yes. class InvalidRecordError(OrderFeedError, ValueError) lets older callers that catch ValueError keep working while new ones catch the job’s class.

WHAT YOU NOW KNOW

  • parse_order raises instead of returning None, so a bad record fails at record 118, not later in a caller.
  • OrderFeedError has one subclass per caller action: skip the record, try again later, or ask a person to fix the key.
  • InvalidRecordError keeps partner, n, field and value as attributes and builds “harbor record 118: qty '2 pcs' is not valid” from them.
DEEP DIVE: pickling custom exceptions, assert and python -O, testing that code raises, exceptions as part of an API

Pickling custom exceptions

An exception crosses a process boundary as a pickle: ProcessPoolExecutor and multiprocessing pickle an error raised in a worker and rebuild it in the parent. BaseException.__reduce__ returns the class, self.args and the instance’s __dict__, so unpickling calls the class with args. For InvalidRecordError, args is the one message string, and the keyword-only __init__ refuses it.

THE CLASS CAN’T BE UNPICKLED, AND THE FIX
import functools
import pickle

err = InvalidRecordError(partner="harbor", n=118, field="qty", value="2 pcs")
pickle.loads(pickle.dumps(err))
# TypeError: InvalidRecordError.__init__() takes 1 positional argument but 2 were given


class InvalidRecordError(OrderFeedError):
    ...  # __init__ as before

    def __reduce__(self):  # rebuild from the fields, not from args
        fields = {"partner": self.partner, "n": self.n, "field": self.field, "value": self.value}
        return (functools.partial(type(self), **fields), ())

In a process pool the parent fails while reading the result, so the pool marks itself broken: every pending future fails with BrokenProcessPool, and the TypeError shows up only in its cause. The fix above is a __reduce__ that rebuilds the object from its fields. Check any exception class that may cross processes with pickle.loads(pickle.dumps(err)).

assert and python -O

assert checks an assumption of your own code. python -O, or the PYTHONOPTIMIZE environment variable, removes every assert statement when the code is compiled, so a check written as an assert is gone in production. Use it for what can be false only through a bug, such as a total that must not be negative. Raise a real exception for bad input, such as record 118.

Testing that code raises

A test for the error path calls parse_order with record 118 inside pytest.raises(InvalidRecordError, match="record 118"). It passes only if that class is raised with a message that contains the pattern. Fields make sharper tests: write with pytest.raises(...) as excinfo: and assert excinfo.value.field == "qty". The testing tutorial’s first chapter shows how pytest.raises works.

Exceptions as part of an API

The classes a function raises are part of its interface, as much as its arguments and its return type. Say in the docstring what a public function raises and when. Renaming or moving a class breaks every except clause that names it, so keep the old name as an alias, OldName = NewName, for a release or two.

ERRORS THIS CHAPTER EXPLAINS

AttributeError: 'NoneType' object has no attribute 'qty'
a function returned None for a failure, and a caller used the result
raise an exception in the function where the problem is found
TypeError: InvalidRecordError.__init__() takes 1 positional argument but 2 were given
unpickling calls the class with args, which holds only the message
add a __reduce__ that rebuilds the object from its fields
your error passes an except Exception clause
the class derives from BaseException
derive it from Exception, through your base class

Keeping the cause: raise from, context and notes

fetch_orders now catches urllib’s HTTPError and raises PartnerUnavailableError("meadow answered HTTP 503") in its place. The traceback still shows urllib’s error, but joined to yours by a line saying another exception occurred while the first was being handled, which reads like a bug in your handler. The URL that failed appears nowhere. The fix is to translate at the edge of your code, where it calls the library, and say that the library’s error caused yours. How do you replace a library’s error with yours without losing what happened?

STEP 01 / 05

THE MAP SO FAR

Fig 6.1The accent chips are new: translation where the job calls a library, and the links that keep the cause.

Two kinds of part are new. The first is raise … from err in parse_order and fetch_orders, the two functions where the job’s code calls a library: int() and decimal in one, urllib and json in the other. They catch the library’s error and raise one of the job’s own classes in its place.

The second is three attributes of every exception object: __cause__, __context__ and __notes__. They keep the original error attached to the new one, along with extra facts. Linking errors this way is called exception chaining, and the traceback prints the whole chain.

STEP 02 / 05

AN ERROR RAISED IN AN EXCEPT BLOCK KEEPS THE FIRST AS CONTEXT

Fig 6.2The accent link is set by Python, not by your code.

When an exception is raised inside an except block, Python stores the exception being handled in the new one’s __context__. Chapter 05’s fetch_orders does exactly that: it catches meadow’s HTTPError 503 and raises PartnerUnavailableError, so the new error’s __context__ is the HTTPError.

The traceback prints both: urllib’s error first, then During handling of the above exception, another exception occurred:, then yours. That line says a second thing went wrong while the first was being handled. For a translation you wrote on purpose it misleads, because the next person to read it goes looking for a bug in the handler.

TRIMMED: URLLIB’S FRAMES LEFT OUT
Traceback (most recent call last):
  File "/srv/orderfeed/src/orderfeed/partner.py", line 26, in fetch_orders
    with urlopen(url, timeout=10) as reply:
         ~~~~~~~^^^^^^^^^^^^^^^^^
urllib.error.HTTPError: HTTP Error 503: Service Unavailable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/srv/orderfeed/src/orderfeed/partner.py", line 32, in fetch_orders
    raise PartnerUnavailableError(f"{partner.name} answered HTTP {err.code}")
orderfeed.errors.PartnerUnavailableError: meadow answered HTTP 503
STEP 03 / 05

RAISE FROM SAYS THE FIRST ERROR CAUSED THE SECOND

Fig 6.3Three ways to raise inside an except block. The accent column is the one to use when translating.

raise PartnerUnavailableError(...) from err stores err in the new error’s __cause__ and sets __suppress_context__ to True. The traceback then joins the two with The above exception was the direct cause of the following exception:. Both tracebacks are still printed, and the line between them now says what you meant.

raise … from None sets the same flag with no cause, so only the new error prints, though __context__ is still kept on the object. Use from err whenever you translate. Use from None only when the original adds nothing a reader needs.

PARTNER.PY: FETCH_ORDERS TRANSLATES EVERY LIBRARY ERROR
def fetch_orders(partner: Partner, day: str) -> list[dict[str, str]]:
    url = f"{partner.url}?date={day}"
    try:
        with urlopen(url, timeout=10) as reply:
            return json.load(reply)
    except HTTPError as err:                     # a subclass of URLError: first
        if err.code in (401, 403):
            raise PartnerAuthError(f"{partner.name} rejected the key: HTTP {err.code}") from err
        if err.code in (429, 503):
            raise PartnerUnavailableError(f"{partner.name} answered HTTP {err.code}") from err
        raise                                    # any other status: a bug, not an outage
    except (URLError, TimeoutError) as err:      # no connection, or a stalled read
        raise PartnerUnavailableError(f"{partner.name} could not be reached") from err
    except json.JSONDecodeError as err:          # a download cut off halfway
        raise PartnerUnavailableError(f"{partner.name} sent a broken file") from err
TRIMMED: URLLIB’S FRAMES LEFT OUT
Traceback (most recent call last):
  File "/srv/orderfeed/src/orderfeed/partner.py", line 26, in fetch_orders
    with urlopen(url, timeout=10) as reply:
         ~~~~~~~^^^^^^^^^^^^^^^^^
urllib.error.HTTPError: HTTP Error 503: Service Unavailable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/srv/orderfeed/src/orderfeed/partner.py", line 32, in fetch_orders
    raise PartnerUnavailableError(f"{partner.name} answered HTTP {err.code}") from err
orderfeed.errors.PartnerUnavailableError: meadow answered HTTP 503
STEP 04 / 05

TRANSLATE AT THE EDGE, SO CALLERS SEE ONLY YOUR CLASSES

Fig 6.4Library errors enter from below. Only the job’s own classes climb above the accent edge.

fetch_orders, in the sample above, catches four kinds of library error. An HTTPError with status 401 or 403 becomes PartnerAuthError, and 429 or 503 becomes PartnerUnavailableError. Any other status is re-raised unchanged: a 404 is a bug to fix, not an outage to wait out. PartnerUnavailableError also covers URLError (no connection), TimeoutError (a read that stalled) and JSONDecodeError: a file cut off halfway may arrive whole next time. HTTPError is caught first because it is a subclass of URLError.

parse_order does the same for the record: KeyError (a missing field), ValueError (a quantity such as '2 pcs') and decimal.InvalidOperation (a price such as '7,50') all become InvalidRecordError. Above these two functions nothing imports urllib’s or json’s classes, so swapping urllib for another HTTP client changes one function.

STEP 05 / 05

ADD_NOTE ADDS A FACT WITHOUT A NEW EXCEPTION

Fig 6.5Follow 1 to 3. The accent note was added by a caller on the way up.

err.add_note(text) appends a line to err.__notes__, and the traceback prints each note under the message. fetch_orders adds the URL it asked for, url: https://orders.meadow.example/v1/orders?date=2026-11-27, before it raises. The fact reaches the person reading without a new class or a longer message.

A caller can add context on the way up. import_partner catches OrderFeedError, adds partner 2 of 3: meadow and re-raises with a bare raise, which sends the same object on with its traceback intact. Notes arrived in Python 3.11.

TWO FRAMES ADD A NOTE EACH
def fetch_orders(partner: Partner, day: str) -> list[dict[str, str]]:
    url = f"{partner.url}?date={day}"
    try:
        with urlopen(url, timeout=10) as reply:
            return json.load(reply)
    except HTTPError as err:
        new = PartnerUnavailableError(f"{partner.name} answered HTTP {err.code}")
        new.add_note(f"url: {url}")        # printed under the message
        raise new from err


def import_partner(partner: Partner, conn: sqlite3.Connection, day: str, place: str) -> int:
    try:
        records = fetch_orders(partner, day)
    except OrderFeedError as err:
        err.add_note(f"partner {place}: {partner.name}")
        raise                               # the same error, one more note
    return save_all(conn, partner, records)
THE LAST THREE LINES OF THE TRACEBACK
orderfeed.errors.PartnerUnavailableError: meadow answered HTTP 503
url: https://orders.meadow.example/v1/orders?date=2026-11-27
partner 2 of 3: meadow

COMMON QUESTIONS

Why not copy the old message into the new one?
A copied message loses the original type and its traceback. from err keeps both, and tools that read the chain, such as the traceback printer and logging, show them.
When is from None right?
When the original is a detail with nothing to add, such as the KeyError behind a “no partner called meadw” message from a lookup in a dict.
Can code read the cause?
Yes: err.__cause__ is the original exception, so a handler could check err.__cause__.code == 503. A field on your own class is cleaner, because the handler then doesn’t depend on urllib.

WHAT YOU NOW KNOW

  • Inside an except block a new error keeps the first as __context__; raise … from err makes it __cause__ and prints “direct cause”.
  • fetch_orders and parse_order are the edge: above them only OrderFeedError classes climb, each carrying the library’s error as its cause.
  • add_note lets import_partner add “partner 2 of 3: meadow” and re-raise the same error, with no new class.
DEEP DIVE: reading a chained traceback, translating timeouts, notes from the standard library

Reading a chained traceback

A chained traceback prints the oldest error first: the cause, then the separator, then the error that reached the top. Read the last block first, because it says what failed in your terms, then read up into the cause for the detail. A chain can be longer than two. The printer follows __cause__, or __context__ when it isn’t suppressed, and stops at an error it has already printed.

The standard library has handlers without from too. urlopen catches the OSError of a failed connection and raises URLError(err) inside the except block, so a refused connection prints the OSError, the “During handling” line, then the URLError. That separator comes from urllib’s code, not from a bug in yours.

Translating timeouts

urlopen wraps an error in URLError only while it sends the request, which covers looking up the name (DNS), connecting and the TLS handshake. A timeout there prints <urlopen error timed out>. Once the request is sent, a stall before the response headers, or in the middle of the body, raises a bare TimeoutError: timed out, which is not a URLError.

timeout=10 applies to each blocking operation, not to the whole download: a server that sends one byte every nine seconds never trips it. For a deadline on the whole call, check time.monotonic() between reads and raise PartnerUnavailableError once it has passed.

Notes from the standard library

Since Python 3.14, json and pickle add notes to serialization errors that say where the bad value sits. json.dumps({"price": Decimal("7.50")}) raises TypeError: Object of type Decimal is not JSON serializable with the note when serializing dict item 'price' under it.

add_note accepts a str and nothing else. add_note(5) raises TypeError: add_note() argument must be str, not int, so format the value into a string first.

ERRORS THIS CHAPTER EXPLAINS

During handling of the above exception, another exception occurred:
an error was raised inside an except block without from
add from err if the translation is deliberate; otherwise fix the handler’s own bug
<urlopen error timed out>
the timeout hit while urlopen was connecting
it is a URLError; catch (URLError, TimeoutError)
TimeoutError: timed out
the server stalled after the request was sent, before the headers or during the body
it is not a URLError; catch TimeoutError too
TypeError: add_note() argument must be str, not int
add_note was given something other than a str
format it first: add_note(f"record {n}")

One place at the top: log once, exit with a status

Every error the job raises is now one of its own classes, with its cause attached. But nothing catches PartnerUnavailableError, so Python’s default handler still prints a traceback into a cron mail nobody reads and exits with status 1, the same status a typo would give. The top of the program needs one handler that decides what is reported, where, and with which status. Where should errors finally be caught, and what should happen there?

STEP 01 / 04

THE MAP SO FAR

Fig 7.1The accent parts are new: one handler at the top, the log it writes and the status it sets.

A boundary is the one place at the top of a program that catches whatever no frame below could handle. In this job it is main(), the first function of yours that runs and the last one an error passes before it leaves the program.

Three parts are new. The handler in main() catches the job’s errors by class. It writes what happened to orderfeed.log, a file someone reads in the morning, and it ends the process with an exit status that says which kind of failure this was. Faint parts arrive in later chapters.

STEP 02 / 04

CATCH BROADLY IN ONE PLACE: THE TOP

Fig 7.2Follow 1 to 5: meadow’s error passes every frame until the accent clause in main catches it.

main() now wraps run_import in a try with three clauses. except PartnerUnavailableError logs one line and exits with status 75. except PartnerAuthError logs one line and exits with 78. except Exception logs the full traceback and exits with 1, because an error nobody expected is a bug. Python tries the clauses in order, so the specific classes come first.

Tonight harbor imports cleanly: 212 orders saved, record 118 skipped, the repeat at record 170 ignored. Then meadow answers 503. Its error climbs through import_partner and run_import, which catch nothing of that class, up to main. The job exits 75, and north is never tried.

Everything below main catches only what it can act on, such as import_partner skipping a bad record. KeyboardInterrupt derives from BaseException, not from Exception, so Ctrl-C still stops the job. A web framework’s request handler and a worker’s loop around each job are boundaries of the same kind: one per request, or one per job.

CLI.PY: THE BOUNDARY IN MAIN()
def main() -> None:
    parser = argparse.ArgumentParser(prog="orderfeed")
    parser.add_argument("--date", required=True)
    args = parser.parse_args()                 # a bad command line exits 2 here
    logging.basicConfig(filename="orderfeed.log", level=logging.INFO,
                        format="%(asctime)s %(levelname)s %(name)s: %(message)s")
    try:
        run_import(PARTNERS, "orders.db", args.date)
    except PartnerUnavailableError as err:
        log.error("%s; the next run will try again", err)
        sys.exit(os.EX_TEMPFAIL)               # 75
    except PartnerAuthError as err:
        log.error("%s; renew the key", err)
        sys.exit(os.EX_CONFIG)                 # 78
    except Exception:
        log.exception("import failed")         # message and traceback
        sys.exit(1)
STEP 03 / 04

LOG THE TRACEBACK ONCE, WHERE YOU HANDLE IT

Fig 7.3The same failure logged two ways. The accent log has one entry per failure.

log.exception("import failed") logs a message at the ERROR level and adds the traceback of the exception being handled. Call it inside an except block, where the error is handled. In the draft below, fetch_orders and import_partner each log the error and re-raise it, and main logs it again. (download is chapter 06’s translating code, moved into a helper.)

One failure now shows up as three entries. Whoever reads the log in the morning can’t tell one failure from three, and an alert that counts errors counts three. A frame that only passes an error on should log nothing: either it handles the error, or it lets the error climb.

At the boundary, an expected failure gets one line without a traceback, because its class and message say everything. log.error("%s; the next run will try again", err) is enough for meadow. An unexpected error gets log.exception, because its traceback is the only way to find the bug. Below the draft is tonight’s log, written once.

A DRAFT THAT LOGS IN EVERY FRAME
def fetch_orders(partner: Partner, day: str) -> list[dict[str, str]]:
    try:
        return download(partner, day)
    except OrderFeedError:
        log.exception("fetch failed")         # first copy of the traceback
        raise


def import_partner(partner: Partner, conn: sqlite3.Connection, day: str) -> int:
    try:
        return save_all(conn, partner, fetch_orders(partner, day))
    except OrderFeedError:
        log.exception("import failed")        # second copy, same failure
        raise
ORDERFEED.LOG TONIGHT, LOGGED ONCE AT THE TOP
2026-11-28 02:00:04,412 INFO orderfeed.job: harbor: 212 saved, 1 skipped, 1 duplicate
2026-11-28 02:00:04,981 ERROR orderfeed.cli: meadow answered HTTP 503; the next run will try again
STEP 04 / 04

THE EXIT STATUS TELLS CRON WHAT HAPPENED

Fig 7.4One row per way the job can end. The accent row is tonight’s.

sys.exit(status) raises SystemExit, and when it leaves the program the process ends with that number. Cron, a deploy pipeline and your shell all read it the same way: 0 is success, and anything else is a kind of failure.

The job uses six statuses. 0 means every partner imported; skipped records are counted in the summary line, not treated as failures. 1 means a bug. 2 is argparse refusing a bad command line before any import starts. 75 is os.EX_TEMPFAIL, a partner was down, and 78 is os.EX_CONFIG, a partner rejected the key. The shell reports 130 after Ctrl-C.

Separate statuses let a monitor act on each kind of failure: page someone on 1 and 78, and let 75 wait for the next run. With the default handler every failure was 1, so a partner’s maintenance window paged someone for nothing.

WHAT THE SHELL SEES TONIGHT, AND FOR A BAD COMMAND LINE
python -m orderfeed --date 2026-11-27
echo $?
# 75
python -m orderfeed
# usage: orderfeed [-h] --date DATE
# orderfeed: error: the following arguments are required: --date
echo $?
# 2

COMMON QUESTIONS

Why not let the default handler print the traceback?
It always exits 1 and writes to stderr, which cron mails or drops. The boundary writes to the log you read, picks a status per kind of failure, and keeps expected failures to one line.
What about errors in threads?
An uncaught error ends only its own thread, and threading.excepthook prints “Exception in thread …:” to stderr while the main thread carries on. Catch inside the thread’s function, or use concurrent.futures, whose result() re-raises the error in the caller.
Should the boundary catch KeyboardInterrupt?
Only to log one line before stopping. Then re-raise it, or exit with 130, so the shell still sees an interrupted job.

WHAT YOU NOW KNOW

  • main() is the boundary: meadow’s PartnerUnavailableError climbs every frame untouched until main catches it.
  • It logs one line for an expected failure, and a traceback with log.exception only for an unexpected one, once.
  • It exits 75 tonight, so cron and a monitor can tell “try later” from a bug (1) or a rejected key (78).
DEEP DIVE: sys.excepthook and its siblings, structured logs, errors in asyncio tasks, error trackers

sys.excepthook and its siblings

sys.excepthook is the default handler itself: Python calls it with the type, the exception and the traceback of any error that leaves the program. Assign your own function to replace it, for example to send uncaught errors to the log. It runs after the error has left main, so it can report but never recover.

Two more hooks cover the other ways an error can go unhandled. threading.excepthook receives errors that end a thread. sys.unraisablehook receives errors Python has nowhere to raise, such as one inside a __del__ method, and prints them as Exception ignored in: …. Both arrived in Python 3.8.

Structured logs

Pass fields with extra=: log.error("%s", err, extra={"partner": "meadow"}) puts a partner attribute on the log record, where a formatter can write it as a JSON key instead of text. Since Python 3.15, logging.basicConfig also takes formatter=, so a JSON formatter needs no handler code.

One trap: logger.exception() called outside an except block logs your message followed by NoneType: None, because there is no exception to show, and raises nothing.

Errors in asyncio tasks

An error raised inside an asyncio task is stored on the task until something awaits it or calls its result(). If nothing ever does, the event loop logs Task exception was never retrieved on the asyncio logger when the task is garbage-collected, often long after the failure. loop.set_exception_handler replaces what happens then. The async tutorial’s chapter on failure covers how errors leave tasks.

Error trackers

Tools such as Sentry install themselves in sys.excepthook and in the logging module. They read the cause chain and the notes, group repeats of one failure into one issue, and count how often it happens. They are a second reader for your errors. The boundary still decides what each failure means, and the exit status still tells cron.

ERRORS THIS CHAPTER EXPLAINS

NoneType: None under a log message
logger.exception() was called outside an except block
use logger.error() there, or pass exc_info=err
--- Logging error ---
a handler or a format string failed, such as a %s with no argument
fix the format arguments; the traceback under it shows the call
Exception in thread Thread-1 (worker):
an error escaped a thread’s function
catch it inside the function, or collect it through concurrent.futures

Errors that go away: retries with backoff

Some failures go away by themselves. Tonight harbor resets the first connection, and chapter 07’s job stops right there with status 75, although harbor would have answered a second later. Meadow is in maintenance and may be back in minutes. Other failures never go away: north rejects the expired key on every attempt, and record 118 always says “2 pcs”. Trying again pays off only for the first kind, and how you wait matters as much as whether you try. Which errors is it safe to retry, how long do you wait, and where?

STEP 01 / 04

THE MAP SO FAR

Fig 8.1The accent chip is new: the retry sits on the network call itself.

A transient error is a failure that may not happen if you try again: a reset connection, a timeout, a server that is briefly overloaded. The job’s transient errors all come from one place, the call in fetch_orders that downloads a partner’s orders.

That call gets a retry: up to three attempts, with a growing wait between them. It sits on the network call itself, inside fetch_orders, so every frame above sees either the orders or one final error.

STEP 02 / 04

RETRY ONLY ERRORS THAT GO AWAY, ON CALLS SAFE TO REPEAT

Fig 8.2Each error with its verdict. The accent rows fail the same way on every attempt.

Retry an error only if waiting can change the answer. A reset connection, a timeout, 503 Service Unavailable and 429 Too Many Requests can all succeed a moment later, and so can a download cut off halfway, which reaches the job as broken JSON. When a 503 or 429 reply carries a Retry-After header, wait at least that long.

Other errors fail the same way every time. 401 and 403 mean the key is wrong, and north’s stays expired until a person renews it. 404 and 400 mean the request itself is wrong. Record 118’s “2 pcs” comes back on every download. Retrying these only delays the report and sends the partner more requests.

The call must also be idempotent: making it twice has the same effect as making it once. HTTP’s standard defines GET, HEAD, OPTIONS, TRACE, PUT and DELETE as idempotent, and POST as not. The job’s download is a GET, so a second attempt changes nothing on the partner’s side.

STEP 03 / 04

WAIT LONGER EACH TIME, WITH JITTER, THEN STOP

Fig 8.3Meadow’s three attempts on one time axis (illustrative). The accent mark is where the job stops trying.

Exponential backoff waits longer before each new attempt. The job allows 3 attempts. Before attempt n + 1 it waits a random time between 0 and min(8 s, 0.5 s × 2ⁿ): up to 1 s before the second attempt, up to 2 s before the third. The 8 s cap matters only in longer loops.

The random part is jitter. Without it, clients that failed at the same moment retry at the same moment too, and a partner coming back from maintenance meets all of them at once. Drawing each wait anywhere between 0 and the limit, which Marc Brooker’s article on backoff calls full jitter, spreads them out.

fetch_orders is now this loop around download(partner, day), chapter 06’s translating code under a new name. It retries PartnerUnavailableError only. Tonight harbor’s first attempt is reset after 0.2 s; after a wait of 0.7 s the second downloads all 214 records. Meadow answers 503 three times in 2.6 s, so the loop adds the note 3 attempts in 2.6 s and re-raises.

PARTNER.PY: FETCH_ORDERS AS A RETRY LOOP
ATTEMPTS, BASE, CAP = 3, 0.5, 8  # seconds


def fetch_orders(partner: Partner, day: str) -> list[dict[str, str]]:
    started = time.monotonic()
    for attempt in range(1, ATTEMPTS + 1):
        try:
            return download(partner, day)     # chapter 06: raises only our classes
        except PartnerUnavailableError as err:   # PartnerAuthError is never retried
            if attempt == ATTEMPTS:
                err.add_note(f"{attempt} attempts in {time.monotonic() - started:.1f} s")
                raise
            time.sleep(random.uniform(0, min(CAP, BASE * 2**attempt)))
    raise AssertionError("not reached")
STEP 04 / 04

RETRIES AT SEVERAL LAYERS MULTIPLY

Fig 8.4Requests to meadow in one night, one bar per design (illustrative). The accent bar retries at one layer.

A first draft of the job retried in three places. The cron entry re-ran a failed job up to three times, import_partner retried a failing partner three times, and fetch_orders retried each download three times. Each layer multiplies the one below it: 3 × 3 × 3 = 27 requests to meadow in one night, against 3 with a single layer.

The extra requests land on a partner that is already struggling, at the moment it tries to recover. Amazon’s Builders’ Library works the same arithmetic for a stack 5 services deep, each retrying 3 times: the database at the bottom sees 243 times the load. Its advice is to retry at a single point in the stack.

Retry at one layer, the one closest to the failing call, and let the others pass the error up. Here that is fetch_orders. import_partner and run_import see one final PartnerUnavailableError, the job exits 75, and the next night’s run is the only outer retry.

COMMON QUESTIONS

Should I use a retry library?
For anything beyond a loop like this one, yes. tenacity (9.2) and stamina (26.2) add backoff, jitter, limits and logging as a decorator, and urllib3’s Retry honours Retry-After by default. The structural patterns tutorial shows how a decorator wraps a function.
Doesn’t cron already retry?
Only the next night, or sooner if a wrapper re-runs failed jobs. That is the outer layer. Keep the in-process retry short, a few seconds here, so the two don’t multiply.
How long should the timeout be?
Long enough for a normal answer with room to spare: 10 s per operation here. Without one, a stalled partner holds the job forever and no retry ever starts.

WHAT YOU NOW KNOW

  • Harbor’s reset and meadow’s 503 are retried; north’s 401 and record 118 are not, because waiting can’t change them.
  • Each wait is random and its limit doubles: meadow fails three attempts in 2.6 s, then the job raises with a note.
  • One retry layer sends meadow 3 requests a night; three layers of three would send 27.
DEEP DIVE: honouring Retry-After, decorrelated jitter, circuit breakers, idempotency keys

Honouring Retry-After

A 503 or 429 reply may carry Retry-After, either a number of seconds or an HTTP date. RFC 9110, HTTP’s standard, defines the header for 503 in section 10.2.3, and RFC 6585 adds it to 429. Read it from err.headers['Retry-After'] on the HTTPError, wait at least that long, and cap it, so a partner that asks for an hour can’t stall a nightly job.

urllib3’s Retry honours the header by default, on 413 replies as well as 429 and 503.

Decorrelated jitter

Full jitter draws each wait from 0 up to a doubling limit. Decorrelated jitter, from the same article by Marc Brooker, draws it from the previous wait instead: sleep = min(cap, random_between(base, sleep * 3)). Both spread clients out far better than a fixed doubling wait. The difference between them matters when thousands of clients retry against one service; for one nightly job, either is fine.

Circuit breakers

A circuit breaker counts consecutive failures per partner. After, say, five in a row it stops calling that partner for a while and fails at once with its own error, then lets one trial request through. It protects a struggling service from a long-running client that calls it thousands of times an hour. A nightly job makes a few calls per partner, so its attempt limit already does that work.

Idempotency keys

RFC 9110 lists the idempotent methods in section 9.2.2: GET, HEAD, OPTIONS, TRACE, PUT and DELETE. POST is not one of them, so APIs that create orders or payments accept an idempotency key: a unique value the client sends with the POST and reuses on every retry. The server stores the first result under that key and returns it for a repeat, so a retried POST creates one order.

The job does the same on the receiving side. Chapter 04’s INSERT … ON CONFLICT(id) DO NOTHING makes saving an order idempotent: a retried download that delivers order H-20877 twice still saves it once.

ERRORS THIS CHAPTER EXPLAINS

HTTP Error 429: Too Many Requests
the partner is rate limiting you
wait at least Retry-After, and send fewer requests
a job that runs for hours against a partner that is down
no attempt limit, or no timeout
set both: a fixed number of attempts and a timeout per operation

Several failures at once: ExceptionGroup and except*

The job exits 75 tonight, and the morning log says meadow was down. It says nothing about north’s rejected key, because the run stopped at meadow and never tried north. One partner’s failure hides the next one’s. The job should try every partner, then report every failure together, and the boundary should handle each kind its own way. How do you report every partner’s failure, and handle each kind?

STEP 01 / 04

THE MAP SO FAR

Fig 9.1The accent chips are new: one raise that carries several errors, and handlers that take them apart.

An ExceptionGroup is an exception that carries several others at once. run_import raises one after it has tried every partner, holding each partner’s failure.

Its counterpart is except*, a kind of clause in main() that handles each class of error inside a group. With these two parts the map is complete.

STEP 02 / 04

ONE EXCEPTION CAN CARRY SEVERAL

Fig 9.2The group holds both failures; each member keeps its own cause, notes and traceback.

run_import now wraps each partner in its own try. When a partner raises an OrderFeedError, the error goes on a list and the loop moves on to the next partner. After the last one, if the list is not empty, it raises ExceptionGroup("2 of 3 partners failed", errors): a message, then the list.

Tonight harbor’s 212 orders are committed first. Meadow fails after 3 attempts, and north, reached at last, rejects the key. The group holds both errors in group.exceptions, and str(group) is 2 of 3 partners failed (2 sub-exceptions).

Printed, the group gets a traceback of its own, then each member in a numbered box with its own traceback and notes. Read the boxes as separate errors: each one still carries the cause chapter 06 attached.

JOB.PY: TRY EVERY PARTNER, THEN RAISE THE FAILURES TOGETHER
def run_import(partners: list[Partner], db_path: str, day: str) -> None:
    errors: list[OrderFeedError] = []
    with closing(sqlite3.connect(db_path, autocommit=False)) as conn:
        for partner in partners:
            try:
                with conn:
                    saved = import_partner(partner, conn, day)
            except OrderFeedError as err:    # this partner failed; try the next
                errors.append(err)
                continue
            log.info("%s: %d saved", partner.name, saved)
    if errors:
        raise ExceptionGroup(f"{len(errors)} of {len(partners)} partners failed", errors)
TRIMMED: EACH MEMBER’S CAUSE AND THE OUTER FRAMES LEFT OUT
+ Exception Group Traceback (most recent call last):
  |   File "/srv/orderfeed/src/orderfeed/job.py", line 58, in run_import
  |     raise ExceptionGroup(f"{len(errors)} of {len(partners)} partners failed", errors)
  | ExceptionGroup: 2 of 3 partners failed (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "/srv/orderfeed/src/orderfeed/partner.py", line 51, in fetch_orders
    |     return download(partner, day)
    | orderfeed.errors.PartnerUnavailableError: meadow answered HTTP 503
    | 3 attempts in 2.6 s
    +---------------- 2 ----------------
    | Traceback (most recent call last):
    |   File "/srv/orderfeed/src/orderfeed/partner.py", line 51, in fetch_orders
    |     return download(partner, day)
    | orderfeed.errors.PartnerAuthError: north rejected the key: HTTP 401
    +------------------------------------
STEP 03 / 04

EXCEPT* HANDLES EACH KIND INSIDE THE GROUP

Fig 9.3Follow 1 and 2: the group splits, and each accent clause runs with the members of its class.

An except* clause handles the members of a group that match its class. Python tries the clauses in order. Each matching clause runs once, with a new group that holds only its matches, and the next clause sees what is left. Unlike except, more than one clause can run.

In main(), except* PartnerAuthError runs with north’s error and sets the status to 78. except* PartnerUnavailableError then runs with meadow’s and keeps the larger number, max(78, 75). The job exits 78, because a person must renew the key, and meadow gets tried again the next night. Both failures are in the log.

Members that no clause matches are re-raised in a smaller group after the clauses, and keep climbing. Two rules from the grammar: except and except* can’t share one try, and an except* block can’t return, break or continue.

CLI.PY: ONE CLAUSE PER KIND OF FAILURE
def main() -> None:
    args = parse_args()
    setup_logging()
    status = os.EX_OK
    try:
        run_import(PARTNERS, "orders.db", args.date)
    except* PartnerAuthError as group:           # north
        for err in group.exceptions:
            log.error("%s; renew the key", err)
        status = max(status, os.EX_CONFIG)       # 78: a person must act
    except* PartnerUnavailableError as group:    # meadow
        for err in group.exceptions:
            log.error("%s; the next run will try again", err)
        status = max(status, os.EX_TEMPFAIL)     # 75
    sys.exit(status)
STEP 04 / 04

A TASK GROUP RAISES ONE FOR YOU

Fig 9.4On the left, one failing task cancels its siblings (accent). On the right, each task catches its own error.

A TaskGroup runs asyncio tasks together and waits for all of them. Fetching the three partners at once means one task per partner, each running fetch_orders in a thread with asyncio.to_thread. The first task that fails cancels the others, and the group raises ExceptionGroup('unhandled errors in a TaskGroup', [...]) holding the errors.

That rule works against this chapter’s goal. North’s 401 would come back first, because a rejected key is not retried, and the group would cancel harbor’s download and meadow’s retries. So one() catches the expected OrderFeedError inside each task and keeps it, as run_import does, and fetch_all raises its own group after the block.

Cancellation is how asyncio stops a task, and it raises an exception of its own inside the task. The async tutorial’s chapter on failure covers how it travels.

EVERY PARTNER AT ONCE, EXPECTED FAILURES KEPT INSIDE EACH TASK
async def fetch_all(partners: list[Partner], day: str) -> dict[str, list[dict[str, str]]]:
    results: dict[str, list[dict[str, str]]] = {}
    errors: list[OrderFeedError] = []

    async def one(partner: Partner) -> None:
        try:
            results[partner.name] = await asyncio.to_thread(fetch_orders, partner, day)
        except OrderFeedError as err:     # expected: keep it, let the others run
            errors.append(err)

    async with asyncio.TaskGroup() as tg:
        for partner in partners:
            tg.create_task(one(partner))
    if errors:
        raise ExceptionGroup(f"{len(errors)} of {len(partners)} partners failed", errors)
    return results

COMMON QUESTIONS

Do I need groups if my code isn’t concurrent?
Only when several independent pieces of work can each fail and you want every failure reported, as with the three partners. Most code raises one exception at a time and never needs a group.
What happens if no clause handles a member?
After the except* clauses, the unmatched members are re-raised in a new group. It climbs like any other exception, to the next handler or to the default handler.
Does contextlib.suppress work on groups?
Since Python 3.12, yes: suppress(PartnerAuthError) removes the matching members from a group and re-raises the rest.

WHAT YOU NOW KNOW

  • run_import tries all three partners and raises one ExceptionGroup holding meadow’s and north’s failures.
  • In main(), except* PartnerAuthError and except* PartnerUnavailableError each run once, with their share of the group.
  • The job exits 78 for north’s key, and the morning log names both partners.
DEEP DIVE: split, subgroup and derive, nested groups, groups from TaskGroup, TaskGroup.cancel()

split, subgroup and derive

group.split(PartnerAuthError) returns two groups, the matching members and the rest, either of which is None when empty. group.subgroup(...) returns only the first. Both accept a class, a tuple of classes, or a function that takes each exception and returns True for a match, and both keep the original’s message, traceback, cause, context and notes.

TAKE THE KEY ERRORS OUT, RE-RAISE THE REST
try:
    run_import(PARTNERS, "orders.db", "2026-11-27")
except ExceptionGroup as group:
    auth, rest = group.split(PartnerAuthError)
    # auth: a group holding the north error, same message as the original
    # rest: a group holding the meadow error, or None if nothing is left
    if rest is not None:
        raise rest

A subclass of ExceptionGroup must override derive(), the method split and subgroup call to build each smaller group. Without it they return plain ExceptionGroup objects, and the subclass’s own fields are gone.

Nested groups

A member can itself be a group, such as a group of partner failures inside a group raised by a TaskGroup. except* and split look through every level, so a clause matches exceptions wherever they sit. The traceback printer shows at most 10 levels of nesting and 15 members per group, then says how many more there are.

Groups from TaskGroup

A TaskGroup raises BaseExceptionGroup instead of ExceptionGroup when a member derives only from BaseException. KeyboardInterrupt and SystemExit are not grouped at all: the TaskGroup re-raises them on their own, so Ctrl-C works as usual. An error raised in the async with body itself also cancels the tasks and joins the group.

Cancelling a task that awaits asyncio.to_thread stops the waiting, not the thread: the download runs to its end and its result is thrown away.

TaskGroup.cancel()

Python 3.15 adds TaskGroup.cancel(), which cancels the remaining tasks on purpose and ends the block without an error. Before it, stopping a group early meant raising an exception of your own inside the group and catching it outside.

ERRORS THIS CHAPTER EXPLAINS

TypeError: catching ExceptionGroup with except* is not allowed. Use except instead.
except* ExceptionGroup names the group class itself
name the member classes, or use a plain except ExceptionGroup
cannot have both 'except' and 'except*' on the same 'try'
a SyntaxError: one try mixes the two kinds of clause
use except* for every clause, or nest a second try
ValueError: second argument (exceptions) must be a non-empty sequence
a group was raised with an empty list
raise the group only when the list is not empty

The whole picture

Here is every part of the job’s error handling on one map, numbered to match the table below.

Find a number on the map, then its row below: what the part does, where it sits and what it decides.

ONE NIGHT, END TO END

Record 118 makes int raise (1), and parse_order raises its own error from it (10). import_partner skips it (6). The repeated order is harmless, and with commits 212 orders for harbor (8). meadow fails 3 attempts (15) and north rejects the key, so run_import raises both as one group (16). main logs each once (12, 13) and exits 78 (14).

  1. 1raise

    stops the line and starts the climb

    where it sits
    the frame that finds the problem
    decides
    nothing; it hands the problem to the caller
    when wrong
    a wrong value returned instead, failing far from its cause
  2. 2the exception object

    carries the error’s type and message up the stack

    where it sits
    created by raise
    decides
    its class decides which handlers can catch it
    when wrong
    a message with no detail, such as a bare ValueError()
  3. 3the climb

    ends each frame early until a handler matches

    where it sits
    every frame between the raise and the handler
    decides
    which lines never run
    when wrong
    work half done: a loop stopped at record 118
  4. 4the default handler

    prints the traceback and exits with status 1

    where it sits
    the interpreter, above main()
    decides
    nothing; it runs when no handler matched
    when wrong
    a traceback in a cron mail and status 1 for every failure
  5. 5the traceback

    records every frame the error left, oldest call first

    where it sits
    on the exception, printed on stderr
    decides
    nothing; it is the record you read
    when wrong
    the line where the error surfaced, which may not be the mistake
  6. 6try and except

    catches a matching error so the frame can carry on

    where it sits
    the frame that can act on the error
    decides
    the first clause whose class matches runs
    when wrong
    a job that reports success with every record skipped
  7. 7the class hierarchy

    groups errors so one clause catches a whole family

    where it sits
    every except clause
    decides
    a clause catches its own class and every subclass
    when wrong
    Ctrl-C ignored, because a bare except: caught it
  8. 8finally and with

    release resources and finish transactions on every way out

    where it sits
    the frame that acquired the resource
    decides
    nothing; the cleanup runs whatever happened
    when wrong
    connections left open and half-written data after a failure
  9. 9your exception classes

    name failures by what the caller should do next

    where it sits
    errors.py, raised by your own code
    decides
    which handler, and so which action, applies
    when wrong
    callers comparing message strings to tell errors apart
  10. 10raise … from

    turns a library’s error into yours and keeps the original

    where it sits
    where your code calls a library
    decides
    nothing; it links the original as the cause
    when wrong
    a log line with your message and none of urllib’s details
  11. 11cause, context and notes

    keep the original error and extra facts on the exception

    where it sits
    the exception object
    decides
    nothing; they add what the traceback prints
    when wrong
    “During handling…” where you meant a deliberate translation
  12. 12the boundary handler

    catches every error left, once, at the top

    where it sits
    main(), or the top of each request or job
    decides
    how each kind of failure is reported
    when wrong
    the same traceback logged three times, or not at all
  13. 13the log file

    keeps the traceback for whoever investigates

    where it sits
    outside the process
    decides
    nothing; it is what you read the next morning
    when wrong
    a message with no traceback, from log.error without exc_info
  14. 14the exit status

    tells the scheduler which kind of failure happened

    where it sits
    the process, read by cron or CI
    decides
    whether a monitor pages someone or waits
    when wrong
    status 1 for a partner outage, paging someone for nothing
  15. 15retry with backoff

    repeats a call whose error goes away on its own

    where it sits
    the one call to the partner APIs
    decides
    which errors get another attempt, and when
    when wrong
    dozens of requests to a partner that is down, or a job that never ends
  16. 16ExceptionGroup

    carries several failures as one exception

    where it sits
    the frame that runs independent units of work
    decides
    nothing; it reports every failure together
    when wrong
    a report naming one partner while the next failure goes unseen
  17. 17except*

    handles each kind of failure inside a group

    where it sits
    the boundary
    decides
    every clause with matching members runs once
    when wrong
    one handler for the whole group that can’t act on each kind
  18. ·the job’s functions

    the frames an error climbs through

    where it sits
    the process
    decides
    nothing about errors, unless they hold a handler
    when wrong
    a handler in the wrong frame: too low to act, or too high to know

THREE THINGS TO KEEP

  • An exception is an object that climbs from caller to caller until a handler catches it, or the program stops.
  • Catch an error only where you can do something about it. Everywhere else, let it climb.
  • Never hide an error. Report it once, with its traceback, at the place that finally handles it.
Read next. Context managers in the design patterns series, for writing your own with, Async Python’s chapter on failure for cancellation and timeouts, and Testing in Python for checking that your code raises what it should.
$ python -m orderfeed --date 2026-11-27; echo $?
78