Use this when handling Python exceptions.
Exceptions · Python Automation
Python exceptions signal errors and are handled with try/except/else/finally. Catch specific exceptions, such as requests.Timeout, and let unexpected ones surface with a traceback.
1. Catch specific exceptions, not bare except.
2. Log with traceback.
3. Clean up with finally/context managers.
4. Raise custom exceptions for domain errors.
5. Exit non-zero on failure.
error → exception → handle or propagate → exit code
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
The negative fixture should deliberately exercise risks such as environment drift, implicit coercion, broad exception handling, blocking/async confusion, shell quoting/subprocess risks, partial writes and non-deterministic external APIs, choosing the cases most relevant to exception taxonomy, propagation, catch scope, cleanup/finally behavior and preserving original cause/traceback rather than swallowing failures.
Step 2 Example Narrow the fault
try:
conn = ConnectHandler(**device)
except NetmikoTimeoutException:
log.warning("%s unreachable", device["host"])
Step 3 Common mistakes Narrow the fault
except Exception: pass.- Catching errors and still exiting 0.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- Catch specific exceptions like requests.Timeout.
- finally always runs for cleanup.
- Let unexpected exceptions show a traceback.
python3 -c 'raise SystemExit(1)'; echo $?— exit codes- Specific exception handling (except ValueError) — precision
- Logging with exc_info — tracebacks
ReferenceWhy it matters1 section · depth on demand
What it is
Exceptions signal errors. Catch the specific exceptions you can handle, add context, and let others stop the script with a non-zero exit code.
ReferenceImportant terms & boundaries2 sections · depth on demand
In depth
Exceptions are Python's mechanism for errors: when something fails, an exception is raised and propagates until a try/except handles it, or the program stops with a traceback. Handling exceptions deliberately decides whether a script retries, skips a target, or stops safely.
import requests
try:
r = requests.get(url, headers=h, timeout=(5, 30))
r.raise_for_status()
except requests.Timeout:
log.warning("timeout calling %s", url); raise
except requests.HTTPError as e:
if e.response.status_code == 404:
return None
raise
finally:
log.debug("request finished")
Catch specific exceptions, keep the original error (raise ... from e when wrapping), and define your own exception classes for domain errors (class PreconditionFailed(Exception)) so callers can react precisely.
Mechanics
The linked authority for bounded mechanics is Python Documentation — Errors and Exceptions; documentation support is separate from observed lab/production Evidence.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Python Automation > Exceptions. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/tutorial/errors.html · confidence 94%Deep reference
Healthy vs suspicious evidence
Output interpretation
For exception taxonomy, propagation, catch scope, cleanup/finally behavior and preserving original cause/traceback rather than swallowing failures, prefer typed fields and stable IDs over human presentation text.