How do I chain exceptions with raise from in Python?

· Category: Python Programming

Short answer

Python supports exception chaining with raise NewException() from original. This sets the __cause__ attribute and produces a cleaner traceback. Omitting from creates implicit chaining via __context__.

Steps

  1. Catch the original exception.
  2. Raise a new exception using from to indicate direct translation.
  3. Use raise ... from None to suppress the original context when it is irrelevant.
def parse_config(path):
    try:
        with open(path) as f:
            return json.load(f)
    except FileNotFoundError as e:
        raise ConfigError(f"Missing config: {path}") from e
    except json.JSONDecodeError as e:
        raise ConfigError(f"Invalid JSON in {path}") from e

class ConfigError(Exception):
    pass

Tips

  • Explicit chaining makes debugging easier by preserving the full causal chain.
  • raise ... from None is useful when wrapping low-level errors into user-friendly messages without clutter.
  • traceback.print_exc() and __traceback__ allow manual traceback manipulation.

Common issues

  • Forgetting from can leave confusing implicit contexts in tracebacks.
  • Catching a broad exception and re-raising a generic one can hide the real failure point.
  • from None suppresses context but does not remove the original exception object from memory.