Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

What is exception chaining, and what is `raise ... from`?

IntermediateConceptExceptions, context managers, files & logging
Answer

raise NewError("...") from exc attaches the original exception as __cause__, and the traceback shows both ("The above exception was the direct cause of..."). This lets you translate low-level errors into domain errors without losing the root cause.

try:
    cfg = yaml.safe_load(path.read_text())
except (OSError, yaml.YAMLError) as exc:
    raise ConfigError(f"cannot load {path}") from exc

raise ... from None suppresses the context, which is occasionally right for user-facing CLI errors.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging