Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 9 · Error handling depthException chaining: `raise X from Y` vs implicit context vs bare re-raisepredict136 / 161
+150 XP
Task
📝 **Task:** Predict the exact 6-line output. Three sub-cases (A, B, C) each construct an exception in a different way and print: (1) the chain walked via __cause__ ?? __context__, and (2) the values of __cause__ / __context__ / __suppress_context__ depending on the case. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

def show_chain(exc: BaseException) -> str:
    parts = []
    while exc:
        parts.append(type(exc).__name__)
        exc = exc.__cause__ or exc.__context__
    return " <- ".join(parts)


# Case A: explicit `raise X from Y`
try:
    try:
        raise ValueError("inner")
    except ValueError as e:
        raise RuntimeError("outer") from e
except RuntimeError as e:
    print(f"A: {show_chain(e)}")
    cause_name = type(e.__cause__).__name__ if e.__cause__ else "None"
    print(f"   __cause__={cause_name}, suppress={e.__suppress_context__}")

# Case B: implicit `raise X` (no `from`)
try:
    try:
        raise ValueError("inner")
    except ValueError as e:
        raise RuntimeError("outer")
except RuntimeError as e:
    print(f"B: {show_chain(e)}")
    cause_name = type(e.__cause__).__name__ if e.__cause__ else "None"
    ctx_name = type(e.__context__).__name__ if e.__context__ else "None"
    print(f"   __cause__={cause_name}, __context__={ctx_name}")

# Case C: bare `raise` re-raise
try:
    try:
        raise ValueError("inner")
    except ValueError:
        raise
except ValueError as e:
    print(f"C: {show_chain(e)}")
    cause_name = type(e.__cause__).__name__ if e.__cause__ else "None"
    ctx_name = type(e.__context__).__name__ if e.__context__ else "None"
    print(f"   __cause__={cause_name}, __context__={ctx_name}")

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…