Python raise from and __cause__
Wrap a parsing failure in an import error while keeping a reference to its cause.
A simple example
raise from and __cause__
- Start with A conversion fails, then gets wrapped
- Do this Read the previous cause
- Result Original conversion failure
Syntax
raise ValueError("Invalid receipt") from problem
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyKeep the original cause of a failed import
A document import fails inside a lower-level operation. Preserve enough information to identify the step that requested the document and the original cause when reporting the failure.
try:
try:
int("paid")
except ValueError as problem:
raise ValueError("Invalid receipt") from problem
except ValueError as problem:
print(problem)
print(type(problem.__cause__).__name__)
Invalid receipt ValueError
The outer error provides the receipt context. Its explicit cause still identifies the original parsing problem.
Trace a missing shipment record
An importer wraps a missing-record error with a message about the batch. Read the message on the preserved underlying cause to identify what the operator should fix.
Trace a malformed count
A report worker wraps a bad numeric field in a higher-level error. Read the message on the preserved underlying cause to identify what the operator should fix.
What to watch for
Only wrap a failure when you can add context. Avoid logging the same exception at every layer.