This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Error Handling, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
Which exception does int("abc") raise?
Answer: ValueError
Why: The text has the right type but an invalid value for int().
Which exception does a missing dictionary key raise?
Answer: KeyError
Why: Square-bracket access on a missing key raises KeyError.
What is the main purpose of try/except?
Answer: To handle an expected failure and recover
Why: A handler should catch a specific, predictable failure and choose a fallback.
When does a finally block run?
Answer: Always, after try and any except/else block
Why: finally is used for cleanup that must happen either way.
Complete the exception type that handles a bad integer conversion.
try:
value = int(text)
except ____:
value = 0Answer: ValueError
Why: int() raises ValueError when the text cannot be converted.
Complete the keyword that begins an exception handler.
try:
value = int(text)
____ ValueError:
value = 0Answer: except
Why: except introduces the block that handles a matching exception.
Complete the exception type raised by a missing dictionary key.
try:
price = order["price"]
except ____:
price = 0Answer: KeyError
Why: Reading a missing key with square brackets raises KeyError.
Complete the block that always runs for cleanup.
try:
print("work")
____:
print("cleanup")Answer: finally
Why: finally runs whether the try succeeds or fails.
What is printed?
try:
print(int("5"))
except ValueError:
print("bad")Answer: 5
Why: The conversion succeeds, so the except block is skipped.
What is the output?
try:
print(int("x"))
except ValueError:
print("invalid")Answer: invalid
Why: The conversion fails, so the handler prints invalid.
What does this code print?
order = {}
try:
print(order["price"])
except KeyError:
print("missing")Answer: missing
Why: The key is absent, so the KeyError handler runs.
What does the program output?
try:
print("try", end=" ")
finally:
print("finally")Answer: try finally
Why: finally always runs, and the first print avoids a newline.
Try the questions first
Open the practice page for Python Error Handling and answer the same 12 questions with instant feedback.