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
- Catch the original exception.
- Raise a new exception using
fromto indicate direct translation. - Use
raise ... from Noneto 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 Noneis useful when wrapping low-level errors into user-friendly messages without clutter.traceback.print_exc()and__traceback__allow manual traceback manipulation.
Common issues
- Forgetting
fromcan leave confusing implicit contexts in tracebacks. - Catching a broad exception and re-raising a generic one can hide the real failure point.
from Nonesuppresses context but does not remove the original exception object from memory.