Library contents

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__

  1. Start with A conversion fails, then gets wrapped
  2. Do this Read the previous cause
  3. Result Original conversion failure
The outer message explains what the caller was doing. The cause preserves the underlying failure.

Syntax

Python 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.py

Keep 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.

First output lineInvalid receipt
lesson.py
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__)
Output
Invalid receipt
ValueError

The outer error provides the receipt context. Its explicit cause still identifies the original parsing problem.

Advertisements

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.

GivenBatch → missing record
Worked resultMissing record

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.

GivenReport → invalid count
Worked resultInvalid count

What to watch for

Only wrap a failure when you can add context. Avoid logging the same exception at every layer.

Documentation for raise from and __cause__