Python Exception Handling 5 — Questions and Answers
Question 1: What is the correct way to define a custom exception that carries an error code?
- class MyError(Exception): pass
- class MyError(Exception): def __init__(self, msg, code): super().__init__(msg) self.code = code (Correct answer)
- class MyError: pass
- def MyError(Exception): pass
Correct 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.
Question 2: What does `sys.exc_info()` return when called outside of an exception handler?
- (None, None, None) (Correct answer)
- (Exception, None, None)
- An empty list
- Raises RuntimeError
Correct answer: (None, None, None)
Outside an active exception handler, `sys.exc_info()` returns `(None, None, None)` indicating no exception is being handled.
Question 3: Which module provides `contextmanager` decorator for creating context managers that handle exceptions?
- functools
- contextlib (Correct answer)
- exceptions
- builtins
Correct 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.
Question 4: In a `try/except/else/finally` block, what is the correct execution order when no exception is raised?
- try → except → else → finally
- try → else → except → finally
- try → else → finally (Correct answer)
- try → finally → else
Correct answer: try → else → finally
When no exception occurs: `try` runs, `except` is skipped, `else` runs, then `finally` always runs last.
Question 5: What does the `__traceback__` attribute of an exception object contain?
- A string with the error message
- A traceback object representing the call stack at the time of the exception (Correct answer)
- The name of the file where the error occurred
- A list of all previous exceptions
Correct 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.
Question 6: What is the safest way to log an exception with its full traceback using the `logging` module?
- logging.error(str(e))
- logging.exception('message') (Correct answer)
- logging.warning(e.__traceback__)
- logging.critical(repr(e))
Correct answer: logging.exception('message')
`logging.exception()` automatically appends the current exception's traceback to the log message when called inside an `except` block.
Question 7: Which exception is raised when an `await` expression is used outside an `async` function?
- RuntimeError
- SyntaxError (Correct answer)
- AsyncError
- TypeError
Correct answer: SyntaxError
Using `await` outside an `async def` function is a `SyntaxError` caught at compile time, not at runtime.
What is the correct way to define a custom exception that carries an error code?