Python Exception Handling 3 — Questions and Answers
Question 1: What is the purpose of the `raise ... from ...` syntax introduced in Python 3?
- To silence the original exception
- To chain exceptions and explicitly set the cause (Correct answer)
- To re-raise the same exception
- To convert one exception type to another silently
Correct answer: To chain exceptions and explicitly set the cause
`raise NewException() from original` explicitly chains exceptions, setting `__cause__` so the traceback shows the causal relationship.
Question 2: Which attribute stores the exception that caused another exception when using implicit exception chaining?
- __cause__
- __context__ (Correct answer)
- __traceback__
- __reason__
Correct answer: __context__
`__context__` is set automatically when an exception is raised while another exception is already being handled (implicit chaining).
Question 3: What does `raise ValueError('bad input') from None` do?
- Raises ValueError and shows the original exception
- Suppresses the exception chain, hiding the original cause (Correct answer)
- Raises None as an exception
- Is a syntax error
Correct answer: Suppresses the exception chain, hiding the original cause
Using `from None` suppresses the exception chain so the original exception context is not displayed in the traceback.
Question 4: How can a custom exception class pass additional data to the handler?
- By overriding __init__ to store extra attributes (Correct answer)
- By using a global variable
- Custom exceptions cannot carry extra data
- By printing to stderr before raising
Correct answer: By overriding __init__ to store extra attributes
Override `__init__` in your custom exception to accept and store extra attributes that handlers can access via the exception object.
Question 5: What is the base class for all non-system-exiting exceptions in Python?
- BaseException
- Exception (Correct answer)
- RuntimeError
- StandardError
Correct answer: Exception
`Exception` is the base class for all regular (non-system-exiting) exceptions; catching it excludes `SystemExit`, `KeyboardInterrupt`, etc.
Question 6: Which exception is NOT a subclass of `Exception`?
- ValueError
- RuntimeError
- KeyboardInterrupt (Correct answer)
- TypeError
Correct answer: KeyboardInterrupt
`KeyboardInterrupt` inherits directly from `BaseException`, not `Exception`, so `except Exception` won't catch it.
Question 7: What happens if no `except` clause matches a raised exception?
- Python prints a warning and continues
- The exception propagates up the call stack (Correct answer)
- The finally block is skipped
- Python automatically converts it to a RuntimeError
Correct answer: The exception propagates up the call stack
If no matching `except` clause is found, the exception propagates to the caller and continues up the call stack until caught or it terminates the program.
What is the purpose of the `raise ... from ...` syntax introduced in Python 3?