Skip to Content

When do you catch an exception, and when do you let it bubble?

Category: Python Fundamentals

Answer

Catch at the layer that knows the user-facing response. Let it bubble everywhere else. A repository should not swallow a SQLAlchemy error; the route layer translates it to a 404 or 500. This keeps the data layer pure and the response layer cohesive.

Concrete examples from the fca project context

Example 1

Repository raises RepositoryError(“not found”); router catches -> 404 JSON.

Example 2

Service layer: try/except around a third-party library; convert to ServiceError.

Example 3

Top-level middleware catches AppError; let other exceptions 500.

Data flow / flow chart

data layer: raise AppError
  service layer: translate
  router: HTTP code
  top: render JSON

Takeaway

Catch at the boundary that turns the error into a response. Each layer translates, every other layer bubbles.