Python Exception Handling 4 — Questions and Answers
Question 1: In a context manager using `__exit__`, what should the method return to suppress an exception?
- None
- False
- True (Correct answer)
- 0
Correct answer: True
Returning `True` from `__exit__` tells Python to suppress the exception; any falsy return value lets the exception propagate.
Question 2: What does `contextlib.suppress(FileNotFoundError)` do?
- Raises FileNotFoundError immediately
- Suppresses FileNotFoundError if it occurs in the with block (Correct answer)
- Logs the error and continues
- Converts the error to a warning
Correct 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.
Question 3: Which exception is raised by `assert x > 0` when x is -1?
- ValueError
- AssertionError (Correct answer)
- RuntimeError
- TypeError
Correct answer: AssertionError
`assert` raises `AssertionError` when its condition evaluates to `False`.
Question 4: What is the effect of running Python with the `-O` (optimize) flag on `assert` statements?
- They run faster
- They are completely removed and never execute (Correct answer)
- They raise OptimizeWarning instead
- They become no-ops that return True
Correct 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.
Question 5: What is `ExceptionGroup` introduced in Python 3.11 used for?
- Grouping exception classes in a single except clause
- Raising multiple unrelated exceptions simultaneously (Correct answer)
- Nesting try blocks
- Logging multiple warnings
Correct answer: Raising multiple unrelated exceptions simultaneously
`ExceptionGroup` allows raising and handling multiple concurrent exceptions at once, primarily useful in async/concurrent code.
Question 6: Which syntax is used in Python 3.11+ to handle individual exceptions from an ExceptionGroup?
- except[] ExceptionGroup
- except* TypeError (Correct answer)
- catch TypeError
- multi-except TypeError
Correct answer: except* TypeError
`except*` (star-except) is new syntax in Python 3.11 for handling specific exception types within an `ExceptionGroup`.
Question 7: What happens when a generator function uses `yield` inside a `try` block and the generator is garbage collected without being fully consumed?
- The try block raises StopIteration
- Python calls GeneratorExit causing the finally block to execute (Correct answer)
- The finally block is skipped
- Python raises RuntimeError
Correct 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.
In a context manager using `__exit__`, what should the method return to suppress an exception?