Module 20 · Building Real Python Applications — topic 7 of 13
Exception handling
Error handling at application scale: an application exception hierarchy, translating low-level errors, handling errors at the user-interface boundary, friendly messages versus logged details, and safe saving with cleanup.
Learning objectives
- Design an application exception hierarchy
- Handle errors at the user-interface boundary
- Keep data safe when operations fail
Definition
In an application, exception handling is a strategy: low-level code raises specific exceptions, the logic layer translates them into application errors, and the boundary (command loop, request handler) catches them, shows friendly messages and logs details.
Introduction
A crash with a traceback is fine for a developer and terrible for a user. Applications need a plan for where errors are caught and what users see.
Why it matters
A consistent strategy means the program never crashes on expected problems, never hides unexpected ones, and never loses data.
Detailed explanation
Define a base exception for the application (class AppError(Exception)) and specific subclasses (NotFound, ValidationError, StorageError).
Raise these from the logic layer with messages written for users ('no expense with id 9').
Translate low-level errors (KeyError, OSError, JSONDecodeError) into application errors with raise ... from, so callers handle one family.
Catch errors at the boundary — the command loop, the request handler — not deep inside logic functions.
Expected errors (AppError) get a friendly message; unexpected ones get a generic message for the user and full details in a log for the developer.
Don't swallow exceptions silently; every except block should report, recover or re-raise.
Protect data: write to a temporary file and replace the original only on success, and clean up in finally.
The program should keep running after a handled error, ready for the next command.
Syntax
- Application exception hierarchy.
- Catch at the boundary.
- Friendly messages, logged details.
Code examples
Application errors at the boundary
ok: 250 error: no expense with id 9
Friendly messages and logged details
Please check your input: invalid literal for int() with base 10: 'abc'
LOG ERROR: unexpected failure: KeyError('missing')
Something went wrong; it has been logged.More examples
Saving safely
save failed: TypeError
[{'amount': 250}] FalseStep-by-step explanation
- Data is written to a temporary file first and only moved over the real file when writing succeeded.
- The second save fails because an object can't be converted to JSON, and the original file is untouched.
- finally removes any leftover temporary file either way.
Expected output
Running “Saving safely” prints exactly:
Practical applications
- Editors that never corrupt a document when saving fails.
- Web servers returning 404 or 400 responses instead of crashing.
Best practices
- Define an application exception hierarchy.
- Handle errors at the boundary.
- Save atomically and log unexpected errors.
Common mistakes
Catching everywhere
Avoid
Prefer
Local catch-alls hide bugs and return wrong data silently.
Important notes
- logger.exception inside an except block records the full traceback in the log.
Key takeaways
- Raise specific application errors.
- Catch at the boundary with friendly messages.
- Protect data with safe saving.
Try it yourself
- 1Add a StorageError raised when the data file is unreadable, and handle it in the command loop.
- 2Make the command loop log unexpected errors and continue.
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.
- AdvancedWhat is printed?