Python raise ... from: exception chaining (3.0+)
What you’ll learn
Section titled “What you’ll learn”- The difference between implicit chaining (
__context__) and explicit chaining withraise ... from(__cause__). - How
from Nonehides the context in tracebacks without deleting it, and how__suppress_context__decides what is shown. - Why
frommatters most when an exception is raised outside theexceptblock that caught the original. - How to translate low-level errors into domain exceptions at a module boundary, add notes and find the root cause in code.
- The mistakes that lose debugging information or leak implementation details.
Summary
Section titled “Summary”When one exception leads to another, Python can record the link. If a new exception is raised while another is being handled, the original is attached automatically as __context__ (implicit chaining). raise NewError(...) from original records the original as __cause__ and tells readers it was the direct cause (explicit chaining). raise NewError(...) from None suppresses the display of the context. Both forms were introduced in Python 3.0 by PEP 3134; from None and the __suppress_context__ attribute were added in Python 3.3 (PEPs 409 and 415). All of it is current in Python 3.14.
The problem it solves
Section titled “The problem it solves”Callers of OrdersPortal’s payment code should catch PaymentUnavailable, not TimeoutError, ConnectionResetError and every other error its dependencies might raise. Translating errors is the right design, but if the translation discards the original, whoever debugs the failure sees “gateway unavailable” and nothing about why.
Implicit chaining covers the case where the new exception is raised inside the except block. It does not help when the error is remembered and raised later, which is exactly what a retry loop does.
Running the samples: each sample is a complete script. Save it as a .py file and run it with Python 3.14 (python3 sample.py). Outputs were produced with CPython 3.14.6; the realistic example uses add_note(), which needs Python 3.11 or later.
class PaymentUnavailable(Exception): pass
def call_gateway(order_id, failures): raise next(failures) # every attempt fails in this demo
def failing_attempts(): return iter([TimeoutError("read timed out after 5s"), ConnectionResetError("connection reset by peer")])
# Before: the real error is stored, then a new one is raised OUTSIDE the# except block. No implicit chaining happens, so the root cause is lost.def charge_before(order_id, failures, retries=2): last_error = None for _ in range(retries): try: return call_gateway(order_id, failures) except OSError as exc: last_error = exc raise PaymentUnavailable(f"{order_id}: gateway unavailable")
# After: name the cause explicitly with `from`.def charge_after(order_id, failures, retries=2): last_error = None for _ in range(retries): try: return call_gateway(order_id, failures) except OSError as exc: last_error = exc raise PaymentUnavailable(f"{order_id}: gateway unavailable") from last_error
for charge in (charge_before, charge_after): try: charge("ORD-1001", failing_attempts()) except PaymentUnavailable as exc: print(f"{charge.__name__}: {exc!r}\n cause: {exc.__cause__!r}\n context: {exc.__context__!r}")Output:
charge_before: PaymentUnavailable('ORD-1001: gateway unavailable') cause: None context: Nonecharge_after: PaymentUnavailable('ORD-1001: gateway unavailable') cause: ConnectionResetError('connection reset by peer') context: NoneWithout from, nothing links the two errors, because the raise runs after the except block has finished. With from last_error, the traceback shows the connection reset and logging tools can report it.
How it works
Section titled “How it works”The raise statement has the form raise [expression ["from" expression]]. Three attributes on every exception record the chain:
__context__is set automatically when an exception is raised while another is being handled, in anexceptorfinallyclause or awithblock’s exit.__cause__is set byraise ... from X.Xmust be an exception instance, an exception class (which is instantiated for you) orNone.__suppress_context__is set toTruewheneverfromis used. The traceback printer always shows__cause__when present, and shows__context__only if__cause__isNoneand__suppress_context__is false.
The next script raises the same domain error three ways and prints the traceback with the frame lines removed, so only the chain structure is visible.
import jsonimport traceback
class OrderImportError(Exception): """Raised when an OrdersPortal order payload cannot be imported."""
BAD = '{"order_id": "ORD-1001", "total": 59.90,}' # trailing comma
def parse_implicit(payload): try: return json.loads(payload) except json.JSONDecodeError: raise OrderImportError("order payload is not valid JSON")
def parse_explicit(payload): try: return json.loads(payload) except json.JSONDecodeError as exc: raise OrderImportError("order payload is not valid JSON") from exc
def parse_suppressed(payload): try: return json.loads(payload) except json.JSONDecodeError: raise OrderImportError("order payload is not valid JSON") from None
def outline(exc): """Print the traceback without the frame lines (which start with spaces).""" for line in traceback.format_exception(exc): for part in line.rstrip("\n").split("\n"): if part and not part.startswith(" "): print(" ", part)
for parse in (parse_implicit, parse_explicit, parse_suppressed): try: parse(BAD) except OrderImportError as exc: print(f"{parse.__name__}: cause={type(exc.__cause__).__name__}, " f"context={type(exc.__context__).__name__}, " f"suppress={exc.__suppress_context__}") outline(exc)Output (the exact JSONDecodeError wording can vary between Python versions):
parse_implicit: cause=NoneType, context=JSONDecodeError, suppress=False Traceback (most recent call last): json.decoder.JSONDecodeError: Illegal trailing comma before end of object: line 1 column 40 (char 39) During handling of the above exception, another exception occurred: Traceback (most recent call last): OrderImportError: order payload is not valid JSONparse_explicit: cause=JSONDecodeError, context=JSONDecodeError, suppress=True Traceback (most recent call last): json.decoder.JSONDecodeError: Illegal trailing comma before end of object: line 1 column 40 (char 39) The above exception was the direct cause of the following exception: Traceback (most recent call last): OrderImportError: order payload is not valid JSONparse_suppressed: cause=NoneType, context=JSONDecodeError, suppress=True Traceback (most recent call last): OrderImportError: order payload is not valid JSONRead the three cases side by side:
- Implicit. The context is shown with “During handling of the above exception, another exception occurred”. That wording suggests the handler itself failed, which misleads readers when the translation was deliberate.
- Explicit
from exc. The banner becomes “The above exception was the direct cause of the following exception”, which states the intent. Note that__context__is still set as well;fromadds a cause, it does not remove the context. from None. Only the new exception is printed, but__context__still holds theJSONDecodeErrorfor anyone inspecting it in a debugger. Suppression is a display decision, not deletion.
traceback.format_exception() and traceback.print_exception() accept chain=False to print only the last exception, and logging’s logger.exception() prints the full chain by default.
Realistic example
Section titled “Realistic example”OrdersPortal’s OrderApiClient exposes one exception hierarchy to callers. A missing order is reported with from None, because the dictionary lookup that detected it is an implementation detail. A malformed response keeps its cause, because the underlying KeyError or JSONDecodeError is exactly what an engineer needs, and add_note() attaches the start of the response body. A helper walks the chain the same way the traceback printer does.
import json
class OrdersPortalError(Exception): """Base class for errors the OrdersPortal client exposes."""
class OrderNotFound(OrdersPortalError): pass
class BadResponse(OrdersPortalError): pass
FAKE_SERVER = { "/orders/ORD-1": '{"order_id": "ORD-1", "status": "shipped", "total": "59.90"}', "/orders/ORD-2": '{"order_id": "ORD-2", "status": "paid"}', "/orders/ORD-3": '<html>502 Bad Gateway</html>',}
class OrderApiClient: def _get(self, path: str) -> str: try: return FAKE_SERVER[path] except KeyError: # The dict lookup is an implementation detail: hide it. raise OrderNotFound(path) from None
def get_total(self, order_id: str) -> float: body = self._get(f"/orders/{order_id}") try: data = json.loads(body) return float(data["total"]) except (json.JSONDecodeError, KeyError, ValueError) as exc: # The low-level error IS useful when debugging: keep it. err = BadResponse(f"unexpected response for {order_id}") err.add_note(f"body starts with: {body[:30]!r}") raise err from exc
def root_cause(exc: BaseException) -> BaseException: """Follow __cause__/__context__ the way the traceback printer does.""" seen = set() while id(exc) not in seen: seen.add(id(exc)) nxt = exc.__cause__ or (None if exc.__suppress_context__ else exc.__context__) if nxt is None: break exc = nxt return exc
client = OrderApiClient()for order_id in ["ORD-1", "ORD-2", "ORD-3", "ORD-9"]: try: print(order_id, "total", client.get_total(order_id)) except OrdersPortalError as exc: root = root_cause(exc) print(f"{order_id} {type(exc).__name__}: {exc} | root: {type(root).__name__}: {root}" f" | notes: {getattr(exc, '__notes__', [])}")Output:
ORD-1 total 59.9ORD-2 BadResponse: unexpected response for ORD-2 | root: KeyError: 'total' | notes: ['body starts with: \'{"order_id": "ORD-2", "status"\'']ORD-3 BadResponse: unexpected response for ORD-3 | root: JSONDecodeError: Expecting value: line 1 column 1 (char 0) | notes: ["body starts with: '<html>502 Bad Gateway</html>'"]ORD-9 OrderNotFound: /orders/ORD-9 | root: OrderNotFound: /orders/ORD-9 | notes: []Callers catch OrdersPortalError and never see json or dictionary errors, yet every BadResponse still carries its root cause for logs and debuggers. The seen set in root_cause guards against cycles in reused exception objects.
Common mistakes
Section titled “Common mistakes”# 1. `from` needs an exception (or None).try: raise ValueError("bad total") from "parse error"except TypeError as exc: print("TypeError:", exc)
# 2. Losing the type: str(exc) keeps the message, drops everything else.try: try: {}["total"] except KeyError as exc: raise RuntimeError(str(exc)) from Noneexcept RuntimeError as exc: print(repr(exc), exc.__cause__)
# 3. A class after `from` is instantiated for you.try: raise RuntimeError("import failed") from ConnectionErrorexcept RuntimeError as exc: print(repr(exc.__cause__))
# 4. Bare `raise` outside an except block has nothing to re-raise.try: raiseexcept RuntimeError as exc: print("RuntimeError:", exc)Output:
TypeError: exception causes must derive from BaseExceptionRuntimeError("'total'") NoneConnectionError()RuntimeError: No active exception to reraise- Copying the message instead of chaining.
raise RuntimeError(str(exc))keeps a fragment of text and loses the original type, traceback and attributes such aserrnoorstatus_code. Chain withfrom exc. - Using
from Noneby reflex. It makes tracebacks tidy and debugging harder. Reserve it for causes that are truly irrelevant to the caller, such as a lookup that only signals “not found”. - Wrapping when you should re-raise. If the handler only logs or cleans up, use a bare
raiseto re-raise the original unchanged, rather than inventing a new exception type. - Raising after the
exceptblock withoutfrom. Retry loops, deferred validation and “collect then report” code raise later, where no implicit context exists. Pass the saved exception tofrom. - Testing only the outer type. Tests should also check the chain when it is part of the contract: with pytest,
excinfo.value.__cause__is available afterpytest.raises. - Passing a string or other non-exception to
from. It fails withTypeErrorat the moment you are already handling an error, which hides the original problem.
When to use it and when not to
Section titled “When to use it and when not to”Use raise ... from exc whenever you translate an exception at a boundary (a library API, a service layer, a parser) and the original helps explain the failure. Use from None when the original is an implementation detail that would confuse the reader. Let implicit chaining do its job for genuine “a second thing went wrong while handling the first” situations.
| Situation | Write |
|---|---|
| Handler only logs or cleans up | raise (bare re-raise) |
| Translate to a domain error, cause is useful | raise DomainError(...) from exc |
| Translate, cause is an irrelevant detail | raise DomainError(...) from None |
Raise later, outside the except block |
raise DomainError(...) from saved_exc |
| Add context without changing the type | exc.add_note("...") then raise (3.11+) |
| Several independent failures to report together | ExceptionGroup (3.11+) |
Compatibility
Section titled “Compatibility”| Version | Change |
|---|---|
| 3.0 | Implicit and explicit exception chaining, raise ... from, __context__ and __cause__ (PEP 3134). |
| 3.3 | raise ... from None (PEP 409) and __suppress_context__ (PEP 415). |
| 3.11 | BaseException.add_note() and __notes__; a bare raise re-raises with any traceback changes made in the except clause. |
| 3.14 | Current release; no changes to chaining semantics. |
Interview questions
Section titled “Interview questions”1. What is the difference between __cause__ and __context__?
__context__ is set automatically to the exception being handled when a new one is raised. __cause__ is set only by raise ... from X and records an intentional “direct cause”. The traceback printer prefers __cause__; it shows __context__ only when there is no cause and the context is not suppressed.
2. After raise B from None, is the original exception gone?
No. from None sets __cause__ to None and __suppress_context__ to True, which hides the context in printed tracebacks. B.__context__ still references the original exception for debuggers and code that inspects it.
3. Why does raise NewError() after a for loop with a try/except inside lose the original error, while the same line inside the except block does not?
Implicit chaining only happens while an exception is being handled. Once the except block exits, there is no active exception, so the new one has no context. Saving the exception and using from saved restores the link explicitly.
4. Senior scenario: OrdersPortal’s public SDK currently leaks requests, json and KeyError exceptions to customers. Design its error handling.
Define a small hierarchy rooted at OrdersPortalError, with subclasses callers can act on (OrderNotFound, AuthenticationFailed, RateLimited with a retry_after attribute, BadResponse). Translate at the transport boundary only, one place, using from exc so logs keep the root cause, and from None only for lookups whose cause is noise. Keep the original error out of the public contract: document the SDK types, not the chained ones, so the HTTP library can change later. Add useful data as attributes or notes (request ID, status code) rather than in message strings, and test both the outer type and, where it matters, __cause__. Ship the hierarchy in a minor release with the new classes subclassing the old leaked ones where possible, so existing except clauses keep working.
Key takeaways
Section titled “Key takeaways”- Exceptions raised while handling another get
__context__automatically;raise ... from excadds an explicit__cause__. from Nonehides the context in tracebacks but keeps it in__context__.- Always use
fromwhen you raise outside theexceptblock that caught the original. - Translate low-level errors into domain errors at boundaries, keeping the cause unless it is pure noise.
- Use
add_note()to add context without changing the exception type.
Related pages
Section titled “Related pages”- Python exceptions basics:
try,except,elseandfinally. - Error handling: raising and defining custom exceptions.
- pytest.raises: asserting on exceptions and their causes in tests.
- Context managers:
__exit__and how exceptions inwithblocks are chained. - Python decorators: wrappers that translate exceptions consistently.
Official references
Section titled “Official references”- The raise statement (Python 3.14 language reference)
- Exception context (Python 3.14 built-in exceptions)
- BaseException.add_note (Python 3.14)
- Tutorial: Exception chaining (Python 3.14)
- traceback module (Python 3.14 docs)
- PEP 3134: Exception Chaining and Embedded Tracebacks
- PEP 409: Suppressing exception context
- PEP 415: Implement context suppression with exception attributes