Catching Only the Errors You Expect
The trustees’ report takes its title from Joan’s settings file, whose text sits in a variable to keep things short.
Her Python function, report_title(), parses the text and catches only json.JSONDecodeError,
the error a hand edit with a stray comma causes. Every other exception passes straight through,
so a bug still stops the script where Joan can see it. In this lesson, you ported that
except line to JavaScript and found out what happens to the errors it doesn’t name:
import json
def report_title(text):
try:
settings = json.loads(text)
return settings["report"]["title"]
except json.JSONDecodeError:
print("settings.json is not valid JSON")
text = '{"report": {"title": "October donations"}}'
print(report_title(text))
Run on October’s settings, Python prints October donations.