Sample questions
Python Errors ContextDifficulty 2
try:
int("abc")
except Exception:
print("A")
except ValueError:
print("B")
What happens when this code runs?
- a"B" is printed, because ValueError is the more specific exception type and Python always matches the most specific except clause first
- bPython raises a SyntaxError at definition time because a more specific except clause appears after a more general one
- c"A" is printed: the first matching except clause (Exception) handles it, so the ValueError clause below is unreachable but not itself an error✓
- dBoth "A" and "B" are printed, because Python evaluates every except clause whose type matches the raised exception's type, running each matching handler once in source order regardless of earlier matches
Explanation:except clauses are tried top to bottom, and the first one whose type matches (via isinstance/issubclass) wins — only one runs. Since ValueError is a subclass of Exception, the first clause catches it and prints "A"; the second clause becomes dead code. Python does not detect this ordering issue as a SyntaxError (only a bare except: must be last).
Python Errors ContextDifficulty 1
In a try/except/finally block, when does the code inside finally execute?
- aAlways, whether or not an exception was raised, including when the try block returns early✓
- bOnly when an exception was raised and caught by a matching except clause
- cOnly when no exception was raised in the try block, since finally is meant to complement a successful else branch rather than run unconditionally on every path
- dOnly when the exception propagates uncaught out of the function
Explanation:finally is guaranteed to run on every path out of the try/except structure: normal completion, a caught exception, an uncaught exception, or even a return/break/continue inside try or except. It exists specifically to run cleanup code unconditionally.
Python Errors ContextDifficulty 2
def parse(s):
try:
n = int(s)
except ValueError:
return None
else:
n *= 2
finally:
print("done")
return n
print(parse("5"))
What is printed?
- a"done" is printed, then None is returned, because the else block does not affect the value of n
- bA ValueError is raised, because int("5") succeeding in try does not allow an else clause to run
- cNothing is printed at all in this run, because "done" only appears on the branch where int(s) raises an exception and control jumps to the except clause
- d"done" is printed, then 10 is returned, since the else block runs when no exception occurred and doubles n before finally executes✓
Explanation:int("5") succeeds, so except is skipped and else runs, setting n to 10. finally always runs next, printing "done". Since no early return happened inside try/except, execution falls through to return n, giving 10.
Python Errors ContextDifficulty 2
A developer wraps value = config["timeout"] in try/except IndexError to guard against a missing key. What happens when "timeout" is absent from config?
- aIndexError is raised, because accessing a missing dict key also raises IndexError, so the except block correctly handles it
- bKeyError is raised, which is not caught by
except IndexError, so the exception propagates uncaught out of the function✓ - cNothing is raised; a missing dict key silently evaluates to None
- dPython raises AttributeError, since dict access requires the key to already exist as an attribute
Explanation:Missing dictionary keys raise KeyError, not IndexError (IndexError is for sequences like list/tuple indexed out of range). Since KeyError is not a subclass of IndexError, the except clause does not match and the exception propagates.
Python Errors ContextDifficulty 1
Which statement about Python's built-in exception hierarchy is correct?
- aZeroDivisionError and ArithmeticError are unrelated classes; catching one never catches the other
- bZeroDivisionError is a subclass of ArithmeticError, so
except ArithmeticError also catches a ZeroDivisionError✓ - cArithmeticError is a subclass of ZeroDivisionError
- dBoth are direct subclasses of BaseException with no shared parent class
Explanation:Python's built-in exceptions form a hierarchy: ZeroDivisionError inherits from ArithmeticError, which inherits from Exception. Catching the parent class ArithmeticError also catches all its subclasses, including ZeroDivisionError and OverflowError.
Python Errors ContextDifficulty 3
def validate(n):
try:
if n < 0:
raise ValueError("negative")
except ValueError:
print("logging")
raise
try:
validate(-1)
except ValueError as e:
print(f"caught: {e}")
What is printed?
- aA RuntimeError is raised, because a bare
raise requires an explicit argument whenever it appears outside of an active exception-handling context in the call stack - bOnly "logging" is printed; the bare
raise swallows the exception, so the outer except never triggers - c"caught: negative" is printed alone; "logging" is suppressed because raise happens before the print takes effect
- d"logging" then "caught: negative" are printed, because a bare
raise inside an except block re-raises the currently handled exception unchanged✓
Explanation:Inside an except block, a bare raise (no arguments) re-raises the exception that is currently being handled, preserving its type, value, and traceback. So "logging" prints first, then the same ValueError propagates to the outer try, which catches it and prints "caught: negative".