Skip to content

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.

Beginner 10 min read·Lesson 300 of 306 in Python Programming

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

Python
class AppError(Exception): ...
class NotFound(AppError): ...
def run_command(handler):
try:
return handler()
except AppError as e:
print("error:", e)
except Exception:
log.exception("unexpected")
print("something went wrong")
  • Application exception hierarchy.
  • Catch at the boundary.
  • Friendly messages, logged details.

Code examples

Application errors at the boundary

Python
class AppError(Exception):
pass
class NotFound(AppError):
pass
def find_expense(expenses, expense_id):
for e in expenses:
if e["id"] == expense_id:
return e
raise NotFound(f"no expense with id {expense_id}")
def handle(command):
try:
return f"ok: {command()}"
except AppError as e:
return f"error: {e}"
expenses = [{"id": 1, "amount": 250}]
print(handle(lambda: find_expense(expenses, 1)["amount"]))
print(handle(lambda: find_expense(expenses, 9)))
Output
ok: 250
error: no expense with id 9

Friendly messages and logged details

Python
import logging
import sys
logging.basicConfig(stream=sys.stdout, format="LOG %(levelname)s: %(message)s", force=True)
def safe_run(action):
try:
return action()
except ValueError as e:
print("Please check your input:", e)
except Exception as e:
logging.error("unexpected failure: %r", e)
print("Something went wrong; it has been logged.")
safe_run(lambda: int("abc"))
safe_run(lambda: {}["missing"])
Output
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

Python
import json
import os
from pathlib import Path
def save(path, data):
tmp = Path(str(path) + ".tmp")
try:
tmp.write_text(json.dumps(data), encoding="utf-8")
os.replace(tmp, path)
finally:
if tmp.exists():
tmp.unlink()
path = Path("expenses.json")
save(path, [{"amount": 250}])
try:
save(path, [{"amount": object()}])
except TypeError as e:
print("save failed:", type(e).__name__)
print(json.loads(path.read_text(encoding="utf-8")), Path("expenses.json.tmp").exists())
Output
save failed: TypeError
[{'amount': 250}] False

Step-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:

TextOutput
save failed: TypeError
[{'amount': 250}] False

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

def total(items):
try:
return sum(...)
except Exception:
return 0

Prefer

Let errors propagate to the boundary, which decides what to show.

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

  1. 1
    Add a StorageError raised when the data file is unreadable, and handle it in the command loop.
  2. 2
    Make 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?
Practise this topic