Errors, Validation, and Debugging · practice
Repair the Cause, Not the Symptom
A program can appear to recover while leaving its real bug untouched.
Imagine that every event record is required to contain these keys:
event = {
"name": "Night market",
"city": "Taipei",
}
The program accidentally asks for another key:
try:
print(event["location"])
except KeyError:
print("Location unavailable.")
The handler prevents a "city" is required, the useful repair is to use the correct required key.
Optional data is different
Sometimes a field truly is optional:
print(event.get("website", "No website listed"))
Chapter 9 introduced .get() for this situation. A missing optional website is ordinary data, not necessarily a bug.
The distinction is in the requirement:
required key missing or misspelled: investigate and repair the data or lookup;
optional key absent: use a documented fallback;
external or uncertain data: validate it at the boundary where it enters the program.
Do not decide based only on whether an
Follow the evidence upstream
When a required lookup raises KeyError:
read the missing key named at the bottom of the traceback;
inspect the
’s actual contents; compare both with the program’s data design;
repair the place that violates that design.
Printing the dictionary temporarily can help during investigation:
print(event)
Remove that diagnostic after the cause is clear.
Recovery should preserve meaning
A fallback such as "unavailable" changes the program’s meaning. It says missing data is acceptable. That may be correct for an optional field, but incorrect for a required one.
Good debugging does more than silence an error. It restores the behavior promised by the program.
A dictionary format requires the key "email", but code looks up "mail" and catches the resulting KeyError. What is the best first repair?
Task
The catalog format requires every item to have the keys "title" and "creator".
The starter program catches a
use the correct required key;
remove the unnecessary
tryandexcept;keep the prepared
.
The final program must print only:
Creator: Octavia E. Butler