Exception Handling Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Exception Handling flashcards as text
In a context manager using `__exit__`, what should the method return to suppress an exception?
Answer: True
Returning `True` from `__exit__` tells Python to suppress the exception; any falsy return value lets the exception propagate.
What does `contextlib.suppress(FileNotFoundError)` do?
Answer: Suppresses FileNotFoundError if it occurs in the with block
`contextlib.suppress` is a context manager that silently swallows the specified exception types without any extra code.
Which exception is raised by `assert x > 0` when x is -1?
Answer: AssertionError
`assert` raises `AssertionError` when its condition evaluates to `False`.
What is the effect of running Python with the `-O` (optimize) flag on `assert` statements?
Answer: They are completely removed and never execute
With `-O`, Python strips all `assert` statements from the bytecode, so they never execute regardless of the condition.
What is `ExceptionGroup` introduced in Python 3.11 used for?
Answer: Raising multiple unrelated exceptions simultaneously
`ExceptionGroup` allows raising and handling multiple concurrent exceptions at once, primarily useful in async/concurrent code.
Which syntax is used in Python 3.11+ to handle individual exceptions from an ExceptionGroup?
Answer: except* TypeError
`except*` (star-except) is new syntax in Python 3.11 for handling specific exception types within an `ExceptionGroup`.
What happens when a generator function uses `yield` inside a `try` block and the generator is garbage collected without being fully consumed?
Answer: Python calls GeneratorExit causing the finally block to execute
Python throws `GeneratorExit` into the generator when it is closed or garbage collected, which triggers any `finally` blocks inside the generator.