Good Code
The good version catches the expected file and JSON failures, then raises a domain error while preserving the original exception.
Lesson 05
Catch specific exceptions at the boundary and preserve the original failure with exception chaining.
import json
class SettingsError(Exception):
pass
def load_settings(path):
try:
with open(path, encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError as error:
raise SettingsError(f"Settings file not found: {path}") from error
except json.JSONDecodeError as error:
raise SettingsError(f"Settings file is invalid JSON: {path}") from errorimport json
def load_settings(path):
try:
return json.load(open(path))
except Exception:
return {}The good version catches the expected file and JSON failures, then raises a domain error while preserving the original exception.
The bad version catches everything and returns an empty config. Permission errors, programmer mistakes, and corrupt JSON all become silent defaults.