Python Exception Chaining and Exception Groups
What you will learn
- Why you sometimes convert one error into another
raise ... from ...and the__cause__attribute- Implicit chaining and
__context__ - Hiding the chain with
from None - Adding notes to an error
ExceptionGroupandexcept*for several errors at once
1. Why change an error?
Low-level code raises low-level errors: ValueError: invalid literal for int() tells the reader nothing about which setting was wrong. A higher layer often wants to raise a better error (ConfigError: port must be a number) while keeping the original for debugging. Python supports this with exception chaining.
2. raise ... from ...
Inside an except block, write raise NewError(...) from original:
def load(t):
try:
return int(t)
except ValueError as e:
raise RuntimeError("could not load config") from e
try:
load("x")
except RuntimeError as e:
print(repr(e.__cause__))
ValueError("invalid literal for int() with base 10: 'x'")
The original is stored in the new error's __cause__ attribute. If the new error is not caught, the traceback shows both, with a line saying how they are linked:
Traceback (most recent call last):
File "k147.py", line 4, in load
return int(t)
ValueError: invalid literal for int() with base 10: 'x'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "k147.py", line 10, in <module>
try: load("x")
~~~~^^^^^
File "k147.py", line 6, in load
raise RuntimeError("could not load config") from e
RuntimeError: could not load config
(The file name is shortened.) Read it from the bottom: the final error is the one the program raised; above it is the direct cause. The readers see the friendly message and the root problem.
Quick check: which attribute holds the original error after `raise New from old`?
__cause__ of the new error.
3. Implicit chaining: context
If a new error is raised while handling another (without from), Python still links them, automatically, in __context__:
def implicit():
try:
1 / 0
except ZeroDivisionError:
raise KeyError("oops while handling")
try:
implicit()
except KeyError as e:
print(repr(e.__context__), e.__cause__, e.__suppress_context__)
ZeroDivisionError('division by zero') None False
The traceback then uses a different sentence:
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
...
KeyError: 'oops while handling'
The two sentences tell you what happened:
| Message in the traceback | Meaning | How it arises |
|---|---|---|
| "The above exception was the direct cause of..." | you meant to convert it | raise New from old |
| "During handling of the above exception, another exception occurred" | possibly a second bug inside the handler | a plain raise or an accidental error in except |
When you see "During handling...", check whether your except block itself has a bug.
4. Hiding the chain: from None
Sometimes the original is an internal detail that would confuse the reader. raise ... from None suppresses the context:
def hide():
try:
int("x")
except ValueError:
raise TypeError("clean message") from None
try:
hide()
except TypeError as e:
print(e.__cause__, e.__context__, e.__suppress_context__)
None invalid literal for int() with base 10: 'x' True
The old error is still stored in __context__, but __suppress_context__ is True, so the traceback leaves it out:
Traceback (most recent call last):
File "k147.py", line 28, in <module>
...
TypeError: clean message
Use it when the original adds only noise. Keep the chain (from e) when the cause helps someone debug.
5. Adding notes
Python 3.11 added add_note, which attaches extra text to an error without changing its message. It is handy for adding context as the error passes upward:
e = ValueError("base")
e.add_note("while reading row 7")
try:
raise e
except ValueError as x:
print(x.__notes__, x)
['while reading row 7'] base
The notes are printed under the error in a traceback:
ValueError: base
while reading row 7
6. Exception groups
Sometimes several things fail at once: ten fields in a form, or many tasks running at the same time (lesson 20.4). Raising only the first error would hide the rest. Python 3.11 added ExceptionGroup, an exception that carries a list of other exceptions:
eg = ExceptionGroup("batch", [ValueError("a"), TypeError("b"), ValueError("c")])
print(eg)
print(len(eg.exceptions))
print(repr(eg))
batch (3 sub-exceptions)
3
ExceptionGroup('batch', [ValueError('a'), TypeError('b'), ValueError('c')])
It takes a message and a list of exceptions. The list is in eg.exceptions.
except*
To handle a group, use except* (with a star). Each except* clause takes the matching members out of the group, as a smaller group:
try:
raise eg
except* ValueError as g:
print("values:", [str(x) for x in g.exceptions], type(g).__name__)
except* TypeError as g:
print("types:", [str(x) for x in g.exceptions])
values: ['a', 'c'] ExceptionGroup
types: ['b']
Rules that differ from the plain except:
- Several
except*clauses can run for one raise, each for its own types. (A plaintryruns only the first match.) - The name (
g) is always a group, even when only one error matches. - Members that no clause handles stay in a group that is re-raised afterwards:
try:
try:
raise eg
except* ValueError as g:
print("handled ValueErrors")
except ExceptionGroup as rest:
print("left over:", repr(rest))
handled ValueErrors
left over: ExceptionGroup('batch', [TypeError('b')])
- You cannot mix
exceptandexcept*in the sametry, and you cannot usereturn,breakorcontinueinside anexcept*block.
split
eg.split(type) divides a group into the matching part and the rest without raising:
matched, rest = eg.split(ValueError)
print(repr(matched))
print(repr(rest))
ExceptionGroup('batch', [ValueError('a'), ValueError('c')])
ExceptionGroup('batch', [TypeError('b')])
A normal except Exception also catches an ExceptionGroup, since the group is itself an Exception. An ExceptionGroup accepts only ordinary exceptions as members; for KeyboardInterrupt and other BaseExceptions, Python provides BaseExceptionGroup (and a TypeError is raised if you try to put one in an ExceptionGroup).
Why not just a list?
A group is an exception, so it can be raised, passed through code that knows nothing about groups, nested, and caught selectively. Libraries for concurrent code (such as asyncio.TaskGroup, lesson 20.5) use it to report every failure.
Worked example: reporting every problem at once
Settings are read with a chained error (so the cause stays visible). Records are checked for all their problems together, which are raised as one group and handled by type.
class ConfigError(Exception):
pass
def read_port(text):
try:
return int(text)
except ValueError as e:
raise ConfigError(f"port must be a number, got {text!r}") from e
def validate(record):
problems = []
if not record.get("name"):
problems.append(ValueError("name is missing"))
try:
age = int(record.get("age", ""))
if age < 0:
problems.append(ValueError(f"age is negative: {age}"))
except ValueError:
problems.append(TypeError(f"age is not a number: {record.get('age')!r}"))
if problems:
raise ExceptionGroup(f"invalid record {record!r}", problems)
try:
read_port("80a")
except ConfigError as e:
print(e)
print("cause:", repr(e.__cause__))
records = [{"name": "Rina", "age": "25"},
{"name": "", "age": "-4"},
{"age": "x"}]
for r in records:
try:
validate(r)
except* ValueError as g:
for err in g.exceptions:
print(" value problem:", err)
except* TypeError as g:
for err in g.exceptions:
print(" type problem:", err)
else:
print("ok:", r["name"])
port must be a number, got '80a'
cause: ValueError("invalid literal for int() with base 10: '80a'")
ok: Rina
value problem: name is missing
value problem: age is negative: -4
value problem: name is missing
type problem: age is not a number: 'x'
| Part | What it shows |
|---|---|
raise ConfigError(...) from e |
friendly message, with the original in __cause__ |
problems list |
collects every problem instead of stopping at the first |
ExceptionGroup(message, problems) |
raises them all as one exception |
two except* clauses |
the second record produces two value problems; the third gives a value problem and a type problem, each handled by its own clause |
else |
still works with except*, for the valid record |
The records are made up. Using ValueError and TypeError as the "kinds" is a teaching choice; a real program would define its own types (lesson 14.4).
Common mistakes
- Raising a new error in
exceptwithoutfrom, which gives the confusing "During handling..." message. - Using
from Nonewhen the cause would help debugging. - Writing
raise eorraise Errorwhen you wanted to re-raise (a bareraisekeeps the original). - Mixing
exceptandexcept*in onetry. - Expecting
except*to give a single exception (it always gives a group). - Using
return,breakorcontinueinsideexcept*. - Putting
KeyboardInterruptorSystemExitin anExceptionGroup.
Key takeaways
raise New(...) from oldlinks the new error to its cause (__cause__); the traceback shows both.- Errors raised while handling another are chained automatically (
__context__) with the message "During handling...". from Nonehides the chain;add_noteattaches extra information.ExceptionGroupcarries several errors;except*handles them by type, possibly running several clauses, and re-raises the rest.- Use chaining to keep root causes; use groups to report many failures together.
Practice
1. What does raise ConfigError("bad") from e store, and where?
Show answer
The original error e is stored in the new error's __cause__ attribute.
2. What do the two traceback sentences mean: "direct cause" and "During handling"?
Show answer
"Direct cause" comes from raise ... from ... (a deliberate link). "During handling" means another error was raised inside an except block without from, which may indicate a second bug.
3. When would you use from None?
Show answer
When the original error is an internal detail that would only confuse the reader, so only the new, clearer error should be shown.
4. How many except* clauses can run for one raised ExceptionGroup?
Show answer
Possibly several, one for each type of member present. Unmatched members are re-raised in a group afterwards.
5. What is the type of g in except* ValueError as g?
Show answer
An ExceptionGroup (even if only one ValueError matched). Its members are in g.exceptions.
6. Write a line that adds the text "in row 3" to an existing error err.
Show answer
err.add_note("in row 3")