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
What is the correct way to define a custom exception that carries an error code?
Answer: class MyError(Exception): def __init__(self, msg, code): super().__init__(msg) self.code = code
Subclass `Exception`, call `super().__init__()` with the message, and store extra attributes like `code` as instance variables.
What does `sys.exc_info()` return when called outside of an exception handler?
Answer: (None, None, None)
Outside an active exception handler, `sys.exc_info()` returns `(None, None, None)` indicating no exception is being handled.
Which module provides `contextmanager` decorator for creating context managers that handle exceptions?
Answer: contextlib
`contextlib.contextmanager` lets you write a generator-based context manager where code before `yield` is setup and code after `yield` (with try/except) handles teardown and exceptions.
In a `try/except/else/finally` block, what is the correct execution order when no exception is raised?
Answer: try → else → finally
When no exception occurs: `try` runs, `except` is skipped, `else` runs, then `finally` always runs last.
What does the `__traceback__` attribute of an exception object contain?
Answer: A traceback object representing the call stack at the time of the exception
`__traceback__` holds a traceback object that can be inspected or passed to `traceback.print_tb()` to display the call stack.
What is the safest way to log an exception with its full traceback using the `logging` module?
Answer: logging.exception('message')
`logging.exception()` automatically appends the current exception's traceback to the log message when called inside an `except` block.
Which exception is raised when an `await` expression is used outside an `async` function?
Answer: SyntaxError
Using `await` outside an `async def` function is a `SyntaxError` caught at compile time, not at runtime.