Python Exception Handling 2 — Questions and Answers
Question 1: What happens when an exception is raised inside a `finally` block?
- It is silently ignored
- It replaces any exception from the try block (Correct answer)
- It is caught by the nearest except clause
- Python exits immediately
Correct answer: It replaces any exception from the try block
An exception raised in a `finally` block replaces any exception that was propagating from the `try` or `except` block.
Question 2: Which built-in exception is raised when a key is not found in a dictionary?
- IndexError
- ValueError
- KeyError (Correct answer)
- AttributeError
Correct answer: KeyError
`KeyError` is raised when a dictionary lookup fails because the specified key does not exist.
Question 3: How do you re-raise the currently-handled exception without losing the original traceback?
- raise Exception()
- raise (Correct answer)
- throw
- raise Exception from None
Correct answer: raise
A bare `raise` statement inside an `except` block re-raises the current exception while preserving its original traceback.
Question 4: What is the output of: `print(1/0)` if wrapped with `except ZeroDivisionError as e: print(e)`?
- 0
- division by zero (Correct answer)
- ZeroDivisionError
- None
Correct answer: division by zero
The `str()` representation of a `ZeroDivisionError` is 'division by zero', which is what `print(e)` outputs.
Question 5: Which clause is executed only when no exception occurs in the `try` block?
- finally
- except
- else (Correct answer)
- pass
Correct answer: else
The `else` clause runs only if the `try` block completes without raising any exception.
Question 6: What does `except (TypeError, ValueError):` accomplish?
- Catches only TypeError
- Catches only ValueError
- Catches either TypeError or ValueError (Correct answer)
- Raises both exceptions
Correct answer: Catches either TypeError or ValueError
Grouping exception types in a tuple within a single `except` clause catches any of the listed exception types.
Question 7: Which exception is raised when you try to access a list index that is out of range?
- KeyError
- ValueError
- IndexError (Correct answer)
- OverflowError
Correct answer: IndexError
`IndexError` is raised when a sequence subscript (index) is out of the valid range.
What happens when an exception is raised inside a `finally` block?