Tutorial / Python

Let a bad JSON file fail with a useful message

Beginner1 min6 Dec 2026

A config loader that swallows every exception returns an empty dict, and the program continues with defaults. The real failure, a trailing comma in the file, shows up an hour later as a missing key.

Separate missing files from bad JSON

Python
import json
from pathlib import Path

def load_config(path):
    file = Path(path)
    try:
        return json.loads(file.read_text(encoding="utf-8"))
    except FileNotFoundError:
        raise
    except json.JSONDecodeError as exc:
        raise ValueError(f"{path} is not valid JSON") from exc

FileNotFoundError stays untouched so the caller can tell a missing file from a broken one. JSONDecodeError becomes a ValueError that names the path, and from exc keeps the line number in the traceback.

  • Do not use a bare except when you only expect a parse failure.
  • Include the path in the message. The parser's line number is useless if you do not know which file it refers to.
  • Pass encoding explicitly. The platform default is a poor guess for a config file.

Related