Skip to content

Exceptions and Error Handling

What an Exception Is

An exception is an error object that interrupts normal program flow. Python raises exceptions when code cannot continue normally.

Useful rule of thumb

  • raise an exception when code cannot continue safely
  • catch an exception when it can add context

Example

Python
def validate_project_name(name: str) -> str:
    cleaned = name.strip()
    if not cleaned:
        raise ValueError("Project name cannot be blank.")
    return cleaned

This is useful because the function fails early and clearly.

Catching an Exception

Sometimes I want to handle an exception and recover:

Python
try:
    task_count = int("not-a-number")
except ValueError:
    task_count = 0

Warning

Note that I didn't need to import ValueError here. It's available in the global namespace.

In the final app, this appears two places:

  • Pydantic raises validation errors for bad payloads
  • FastAPI raises HTTPException for missing records or forbidden actions

Intentional error handling makes code easier to debug.