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 iftryraised nothing; keep "success-only" code here so it is not accidentally covered by theexcept.finally: always runs, even onreturnor 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()
More on Exceptions, context managers, files & logging
Why is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow does a `with` statement work, and why use it for files?BeginnerHow do you write your own context manager?Advanced