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

logger.exception("Failed to process order %s", order_id)

logger.exception automatically includes the traceback.

Next up in your learning path