Skip to main content

Python try/except Patterns

Error Handling

try/except/else/finally

Structure your exception handling using all four clauses for clarity.

Template

try:
payload = parse(raw)
except json.JSONDecodeError as exc:
logger.error("Invalid JSON: %s", exc)
raise
else:
process(payload)
finally:
clean_up()
  • else runs when no exception occurs.
  • finally runs regardless—release resources there.
  • Catch specific exceptions whenever possible.

Logging

import logging

logger = logging.getLogger(__name__)

try:
process(order_id)
except Exception:
logger.exception("Failed to process order %s", order_id)

logger.exception automatically includes the traceback. Call it inside an except block.

Next up in your learning path