Module 13 · File Handling — topic 15 of 15
File exceptions
Errors that file operations raise — FileNotFoundError, FileExistsError, PermissionError, IsADirectoryError, UnicodeDecodeError, JSONDecodeError — and how to handle them gracefully.
Learning objectives
- Recognise common file-related exceptions
- Handle decoding problems
- Write robust file-loading functions
Definition
File operations raise exceptions when something goes wrong: the file is missing, already exists, isn't accessible, is a directory, or contains data that can't be decoded. Most derive from OSError.
Introduction
Files live outside your program: users delete them, other programs lock them, and they arrive in unexpected encodings. Robust programs expect these problems.
Why it matters
Handling file errors well turns crashes into clear messages such as 'settings file is not valid JSON (line 2)', which users and developers can act on.
Detailed explanation
FileNotFoundError: the file or folder doesn't exist. FileExistsError: creating something that already exists (mode "x", os.mkdir).
PermissionError: the operating system denies access. IsADirectoryError / NotADirectoryError: a folder was used where a file was expected or vice versa.
All of these derive from OSError, which also has errno and filename attributes describing the problem.
UnicodeDecodeError (a ValueError) occurs when bytes can't be decoded with the chosen encoding. Options: use the correct encoding, or errors="replace" to substitute � for bad bytes.
Data-format errors are separate: json.JSONDecodeError for invalid JSON, csv.Error for malformed CSV, ValueError when converting fields.
Catch specific exceptions and give helpful messages; let truly unexpected errors propagate.
Checking os.path.exists first doesn't remove the need for try/except, because the file can change between the check and the open.
Syntax
- Most file errors are OSErrors.
- Decoding errors are separate.
- Handle each with a clear message.
Code examples
Common OSErrors
FileNotFoundError True FileExistsError True FileExistsError True FileNotFoundError True
Decoding problems
UnicodeDecodeError at byte 3 caf� café
More examples
A robust configuration loader
good.json -> ({'debug': True}, 'ok')
missing.json -> ({}, 'missing - using defaults')
bad.json -> ({}, 'invalid JSON (line 2)')
binary.json -> ({}, 'not UTF-8 text')Step-by-step explanation
- Each failure mode gets its own clear message instead of a traceback.
- UnicodeDecodeError is caught before JSONDecodeError because both are ValueErrors and need different messages.
- JSONDecodeError reports the line number of the problem, which helps users fix the file.
Expected output
Running “A robust configuration loader” prints exactly:
Practical applications
- Desktop apps that start with defaults when settings are missing or corrupt.
- Import tools that report which uploaded file has the wrong encoding.
Best practices
- Catch specific file exceptions with helpful messages.
- Use the correct encoding, or errors="replace" deliberately.
- Prefer try/except (EAFP) over existence checks.
Common mistakes
Check-then-open race
Avoid
Prefer
The file can disappear between the check and the open.
Important notes
- This completes the File Handling module; next comes organising code into modules and packages.
Key takeaways
- File errors are mostly OSError subclasses.
- Decoding problems raise UnicodeDecodeError.
- Handle each failure with a clear message.
Try it yourself
- 1Write read_lines(path) that returns [] for a missing file and raises a clear error for undecodable files.
- 2Extend load_config to also catch IsADirectoryError when the path is a folder.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateOpening a missing file for reading raises which exception?