Python

Lesson 05

Exception boundaries

Catch specific exceptions at the boundary and preserve the original failure with exception chaining.

Good Code

settings.py
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 error

Bad Code

settings.py
import json


def load_settings(path):
    try:
        return json.load(open(path))
    except Exception:
        return {}

Review Notes

What to review

Good Code

The good version catches the expected file and JSON failures, then raises a domain error while preserving the original exception.

Bad Code

The bad version catches everything and returns an empty config. Permission errors, programmer mistakes, and corrupt JSON all become silent defaults.

Takeaways

  • Specific exceptions make failure modes reviewable; blanket catches hide the bug you need to see.