Errors and debugging
Project: resilient study log reader
Read JSON safely and report missing files, malformed JSON, and invalid session data.
Lesson 38 of 63
Reading: about 3 min
Lesson + practice: about 19 min
Difficulty: Beginner
On this page4 sections
Create safe_study_log.py in a fresh practice folder. It reads study_log.json from the current working directory when that file is present. It reports a clear message for a missing file, invalid UTF-8 text, malformed JSON, or invalid sessions.
Build the reader
import json
from pathlib import Path
def total_minutes(path: Path) -> int:
"""Return the sum of valid session minutes in a JSON list."""
sessions = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(sessions, list):
raise ValueError("study log must be a list")
total = 0
for session in sessions:
if not isinstance(session, dict):
raise ValueError("each session must be an object")
subject = session.get("subject")
if not isinstance(subject, str) or not subject.strip():
raise ValueError("subject must be nonblank text")
minutes = session.get("minutes")
if type(minutes) is not int or minutes <= 0:
raise ValueError("minutes must be a positive integer")
total += minutes
return total
try:
total = total_minutes(Path("study_log.json"))
except FileNotFoundError:
print("Study log not found")
except UnicodeDecodeError:
print("Study log is not UTF-8 text")
except json.JSONDecodeError:
print("Study log is not valid JSON")
except ValueError as error:
print(f"Invalid study log: {error}")
else:
print(f"Total study time: {total} min")Study log not found
Why this works
The reader separates three stages: read UTF-8 text, parse JSON, then validate the resulting Python values. Each stage can fail differently. FileNotFoundError identifies a missing path, UnicodeDecodeError identifies invalid UTF-8, JSONDecodeError identifies malformed JSON text, and ValueError reports a valid JSON shape that violates the study-log rules. Each session needs a nonblank text subject and a positive integer duration.
Check three cases
Run in the fresh folder before adding study_log.json and expect "Study log not found". Then copy the valid Chapter 6 file into that folder and expect 65 minutes. Finally, replace its contents in this practice copy with invalid JSON, confirm the JSON message, and restore the valid copy. This program does not overwrite the log.
Which problems does this reader handle?
Reveal answer
A missing file, invalid UTF-8 text, malformed JSON, and session data with a missing or blank subject or an invalid minute count.
Try another case
If the file contains valid JSON text {"minutes": 25} rather than a list, which message appears?
Check your answer
Reveal answer
The reader prints "Invalid study log: study log must be a list" because parsing succeeds but the top-level shape is wrong.
Your progress
Reveal the check answer or reach the end to complete this lesson.