Skip to the solution
MediumBackend5 min read

How do you raise and split ExceptionGroups manually?

551 views

The problem

Question presented to candidate: "Forget asyncio for a moment. Suppose you validate a form or process a batch, and you want to report every failure at once instead of stopping at the first one. How do you raise an ExceptionGroup yourself, and how do you take one apart with except*, split() and subgroup()?"

What a strong answer should cover:

  • Raising: collect exceptions in a list and raise ExceptionGroup("message", errors); the list must be a non-empty sequence of exception instances; ExceptionGroup only accepts Exception subclasses, BaseExceptionGroup takes any and picks the right class (Python 3.11+, PEP 654).
  • Catching: except* T handles the matching part of a group (every leaf, nesting kept); several except* clauses can each run once; unhandled parts and errors raised in handlers are re-raised as a group; a naked exception is wrapped.
  • Splitting: eg.split(cond) returns (match, rest), eg.subgroup(cond) returns only the match; cond is a type, a tuple of types or a predicate (which also sees the groups themselves); no match gives None; nesting, __traceback__, __cause__, __context__ and __notes__ are kept.
  • Subclasses: override derive() so split / subgroup rebuild your class with its extra fields; otherwise they produce plain ExceptionGroups.
  • Rules: except and except* cannot mix in one try; except* ExceptionGroup is a TypeError; no break / continue / return in an except* block.

Code / implementation expected: Yes β€” raise a group of validation errors, catch it with except*, and show split() on a nested group.

  • exceptions
  • exceptiongroup
  • asyncio

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

5 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonRaise a group, catch with except*, split and subgroup it
PythonConstructor rules, derive(), naked exceptions and except* rules

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 80 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is a decorator factory (a decorator with arguments)?

Continue