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 depthcontextlib.suppress — quietly skip specific exceptionspredict137 / 161
+150 XP
Task
📝 **Task:** Predict the exact 5-line output. Five blocks exercise suppress in different shapes: exact-match, subclass-match, unrelated-exception-still-raises, multiple-types (twice). Predict each event line. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from contextlib import suppress


events: list[str] = []


# A: exact match — FileNotFoundError suppressed.
with suppress(FileNotFoundError):
    open("/nope/missing.txt")
events.append("A: continued")

# B: subclass match — FileNotFoundError IS-A OSError, so suppress(OSError) still catches it.
with suppress(OSError):
    open("/nope/missing.txt")
events.append("B: continued")

# C: unrelated exception still raises through the with block.
try:
    with suppress(FileNotFoundError):
        raise ValueError("not file")
except ValueError as e:
    events.append(f"C: caught {e}")

# D: multiple types — KeyError suppressed by suppress(KeyError, IndexError).
with suppress(KeyError, IndexError):
    {}.pop("missing")
events.append("D: continued")

# E: same suppress shape, IndexError this time.
with suppress(KeyError, IndexError):
    [][5]
events.append("E: continued")

for e in events:
    print(e)

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…