Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

How does `try` / `except` / `else` / `finally` work?

BeginnerConceptExceptions, context managers, files & logging
Answer
  • try: code that may raise.
  • except SomeError as e: runs if that exception (or a subclass) is raised.
  • else: runs only if try raised nothing; keep "success-only" code here so it is not accidentally covered by the except.
  • finally: always runs, even on return or an uncaught exception; for cleanup.
try:
    resp = s.get(url, timeout=5)
    resp.raise_for_status()
except requests.HTTPError as e:
    log.error("HTTP %s from %s", e.response.status_code, url)
    raise
else:
    data = resp.json()
finally:
    metrics.calls.inc()
All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging