Naar hoofdinhoud
🔒 Voorbeeldmodus. De eerste vijftien Foundations-lessen zijn gratis; deze is Pro. Start een 7-daagse trial om de editor, AI-hints en de rest van het curriculum te ontgrendelen. Kaart vereist, op elk moment opzegbaar in Dashboard.Start 7-daagse trial →
← CursussenSenior Deep-DivesModule 9 · Error handling depthcontextlib.suppress — quietly skip specific exceptionspredict137 / 161
+150 XP
Opdracht
📝 **Taak:** Voorspel de exacte uitvoer van 5 regels. Vijf blokken oefenen onderdrukking uit in verschillende vormen: exacte match, subklasse-match, niet-gerelateerde uitzondering-nog-raises, meerdere typen (tweemaal). Voorspel elke gebeurtenislijn. 📋 Implementeer bovenstaande functie. Tests worden automatisch uitgevoerd. 💡 **Hint:** Herlees de theorie als je vastloopt.
Voorspel uitvoer

Lees de code zorgvuldig

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)

Wat zal het programma uitprinten? Schrijf hier:

💬 Discussie

Wees de eerste — stel een vraag of deel een tip.
Log in om mee te doen aan de discussie. Lezen is gratis.
Discussie laden…