Skip to content

ADR 0007: Exceptions

Status: Final Type: Feature Created: 2026-07-27 Amends: 0006 (a CPython error becomes a catchable POST exception), 0026 (a handled exception record is released) Amended-By: 0011 (the pending slot becomes per-task; the parent table; four concurrency names join), 0030 (IndexError and KeyError join the vocabulary), 0033 (UnboundLocalError and its base NameError join it, the one second level of the parent table), 0075 (OverflowError is raised where CPython raises it on a big int) Related-ADRs: 0006 (the FFI directions this crosses), 0033 (the placeholder discipline). It derives from arbitrations A1 and A15 and upstream question U2.

Context

Spec §5.1 permits try/except/finally with scalar exceptions only and no groups. Before this ADR a CPython error aborted the process, so one bad request took a whole compiled service down; and a compiled language with no way to raise is a language whose partial failures are all fatal.

Decision

  1. The vocabulary is a closed set of builtin exception types, shallow, declared once: the frontend maps except ValueError: to a code and the runtime's name/parent table is generated from the same declaration, so the two cannot drift. A name enters the vocabulary only with a use case behind it (assert brought AssertionError; the dict rung brought KeyError and IndexError, whose KeyError.__str__-is-repr subtlety had kept them out until repr of a Str existed; the checked read brought UnboundLocalError under NameError, which is why the parent table has one second level). CPython's intermediate abstract classes (BaseException, ArithmeticError, LookupError) are absent, and absence cannot produce a wrong answer: naming one is a diagnostic. Relations between names that are present all agree with CPython's.

  2. "Scalar" means a type code and a message, only. There is no args tuple, attribute dict, traceback object or group. except E as e binds an opaque Exc; the POST operations on it are str(e) (CPython's str(exc), exactly), raise e, a field of a class the script defines (rule 9), and passing it outward across the FFI.

  3. The lowering is an error return through a per-task pending slot. raise allocates a record, parks it, and branches to the innermost handler or to a block returning a placeholder of the declared type. Signatures are unchanged and the lowering needs no unwinder, setjmp or landing pad, so a call to a possibly-raising function costs one test of the slot and one predicted-never-taken branch, identically on all backends by construction. The placeholder is not read: callers check the slot before looking at the result; a return type with no placeholder refuses.

The test of the slot is a load where nothing else can write it. In an executable that starts no task and embeds no CPython, the build compiles the runtime with -D__PP_ONE_THREAD and the slot is a plain global, which the runtime exports as ir.EXC_SLOT_ONE_THREAD. The backends are told so (Backend.emit(module, one_thread=...)): LLVM defines __pp_exc_pending as an alwaysinline load of it, and QBE writes the load in place of the call, since neither one's output passes through a link step that would inline the call. In every other build the slot is static and thread-local and both backends keep the call. A backend that read the slot there would find no symbol and fail to link, which is the safe failure: a thread-local descriptor read as a pointer would report an exception that is not there. tests/b_integration/test_exc_pending_inline.py covers both cases. Threaded builds (a library, an extension module, a pygo program) pay the call on LLVM and QBE.

A program that does not raise pays no cost. can_raise is computed per function and propagated to a fixpoint over the call graph; a check is emitted only after a call to a callee that can raise. Release elides assertions entirely, so release IR stays byte-stable, which protects QBE's shape-matched passes.

The analysis is the first estimate; the lowered function is the judge. The analysis reads source. A raise synthesized at lowering (an unpack arity guard, a runtime-raising method like .decode, a call into a CPython object) has no source raise for it to see. An invisible synthesized raise is an exception swallowed at the first frame boundary, the one failure this lowering has no other guard for. So once a function's unreachable blocks are pruned, a remaining block that leaves with an exception in flight, in a function the analysis did not mark, records the function on the module (Module.unmarked_raisers). compile_source then compiles the module again with those functions as direct raisers, so the fixpoint marks their callers too, and repeats until the two agree, as it does for the standard library's generic instances (A166). A vectorized kernel is exempt, since it terminates where it raises, and so is a script's top level, whose one caller, the driver, checks the slot unconditionally. A body that failed to lower is not judged. A program the analysis reads correctly compiles once.

  1. The exception runtime is one linked unit for all backends. It owns mutable per-task state; a static copy per translation unit would give each module a separate pending slot, so an exception raised in one would be invisible to the other.

  2. assert reuses the machinery: the failure helpers are constructors over the slot raise uses, so try: assert x / except AssertionError: behaves exactly as interpreted; the message is lowered inside the failure block, evaluated only on failure, as CPython evaluates it.

  3. CPython → POST: one scalar exception with an opaque handle. A Python exception raised inside an FFI call is mapped to a POST code by CPython's subclass test (most-derived first, so a json.JSONDecodeError arrives as the ValueError it is), with the message taken eagerly at the boundary, which keeps the exception runtime free of any CPython dependency, so a --pure program can raise. A subclass POST cannot name arrives as Exception, catchable by exactly that; a non-Exception (SystemExit, KeyboardInterrupt) gets a parentless foreign code that POST cannot name, and propagates (both exact). FFI helpers are no-ops while an exception is pending or when handed NULL (CPython's errors-propagate-through-NULL discipline), which lets the frontend check once per statement, with an immediate check after each inward conversion, where a Python value becomes a POST value.

  4. POST → CPython: the original object, re-raised. A propagating compiled callback sets the interpreter's error indicator and returns NULL (the C-API convention), so a failing compiled handler answers 500 and the process serves the next request. An exception that came from CPython re-raises the original object: traceback, args, __cause__ and exact subclass persist through a round trip through compiled code that could represent none of them. An Exc also converts outward like any value, so logging.error(e) hands Python the real exception.

  5. promote() answers None for an unrecognised pairing, _holds derives from it, and the operator paths reject by the opaque property, so the default answer for an unknown type pairing is no. This rule was bought by this ADR's type (the second non-numeric type to walk into a permissive fallback) and makes later ones safe on the day it is introduced.

  6. A script may define exception classes. class E(Exception): pass (a docstring or pass as the body), and subclasses of it, above their use. A record of one takes the code of its nearest builtin ancestor, so except Exception and except ValueError match it through the vocabulary's parent table, and it also has a class number. The numbers come from a depth-first walk of the classes the script defines, so a class and its subclasses are a contiguous range and except E is one range test (__pp_exc_matches_user). The record's name is the class's, which the uncaught report prints, and str(e) is the record's message, as for a builtin (a KeyError subclass quotes it, as CPython's does).

Such a class may have one __init__ whose statements store into self. Its body is that of an ordinary class, synthesized beside the exception (__pp_excdata_E) and compiled as one. raise E(args) evaluates the arguments once, in order; the record's message is what CPython's BaseException makes of them whatever __init__ does, str(args[0]) or empty. Then the fields are stored in an instance of the synthesized class, which the record holds. except E as e: reads them, e.field, borrowed from the record; except Exception as e: catches the same record, message intact.

  1. A record is counted. raise of a new record gives its one reference to the pending slot. A handler's take moves it into a frame slot, one per handler nesting depth, which the next take at that depth or the frame's exit releases. A bare raise or raise e of a caught record retains it first, so the pending slot holds a separate reference. At zero the record releases its name, its message and its fields' instance, and is freed. The C units each pair a raise with a new record; those that take one either raise it again or keep it. A handler that no code can reach declares no slot, so a try around code that cannot raise still costs nothing. Since the record may release an instance, a program that can raise links the object unit.

The refusal boundary

raise X from Y is refused: POST has no attribute to observe __cause__ with, and dropping the cause silently is the difference this compiler exists to prevent. Exception groups and except* and traceback values are refused. So are return inside finally and break/continue out of a try that has one: each needs an exit path through the finally that this lowering lacks; a jump that silently skips a finally is a silent semantic change. A constructor with more than one argument is refused (its str() is a tuple repr). Of the classes a script defines, four shapes are refused. A body other than rule 9's is one, since the record has a message and one instance of fields. A subclass of a class with fields is another, so that a handler for one always reads that class's fields. A subclass of SystemExit and a decorated class are the last two. A library build refuses them all: the exception would reach a CPython caller as its builtin ancestor, where the interpreted module raises the class.

Two positions cannot propagate, and terminate instead. A vectorized kernel runs inside NumPy's broadcast loop with no way to say "and it raised"; returning placeholders would hand NumPy an array of them. The stable C ABI has the same limit: C99 has no exceptions, and a C caller cannot interpret a placeholder. A caller that wants to handle the exception should be a CPython caller, where rule 7 gives it a real one.

OverflowError is raised where CPython raises it: a float too large for a double, a big int reaching a C integer (A191), int.to_bytes. The overflow of a 64-bit int (a library's, an extension module's, a --no-grow-ints executable's) raises nothing: it stops a debug build, uncatchably, and wraps in release (0002). CPython has no such exception to raise, since its int grows. An executable's int grows too (0075).

Consequences

  • A compiled service keeps running through failures: a raising handler answers 500, a caught FFI failure answers what the program says, the next request is served, byte-identical to the interpreted run.
  • An uncaught exception exits 1 with the last line of CPython's traceback, as CPython does; an abort did neither.
  • What stays unreleased is bounded: a record that reaches the top of the program (the process ends); one a C unit keeps (pygo's failure list); a CPython original that a record holds (owned and never released, 0006).
  • The pending check is one load and one branch in a one-thread executable on every backend: spectral_norm's inner loop calls a raiser, and per iteration LLVM runs at 575 µs, as before the check existed, and QBE at 2,110 against 1,875 without the check, since QBE has no optimizer to fold the load, compare and branch.

Alternatives considered

  • Unwinding (setjmp/landing pads): rejected, because three backends would need three mechanisms, while the error return is identical on all three by construction and is the mechanism cancellation delivery reuses.
  • Reconstructing CPython exceptions at the boundary: rejected, because the round trip would lose traceback, args, cause and subclass, while keeping the original makes "nothing is lost" literally true.
  • A tolerant vocabulary (accept any except NAME: and match at runtime): rejected, because an unknown name silently never matching is the accept-then-wrong shape; a diagnostic is exact.