โ† All Python Flashcard Decks

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

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

  3. Which exception is raised by `assert x > 0` when x is -1?

    Answer: AssertionError

    `assert` raises `AssertionError` when its condition evaluates to `False`.

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

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

  6. 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`.

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