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.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?BeginnerHow do you write your own context manager?Advanced