Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Exceptions · Python Automation

Direct answer

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.

When to use this

Use this when handling Python exceptions.

First 30 seconds

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.

Operational verification

error → exception → handle or propagate → exit code

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
Python automation runtime
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformPython automation runtime · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when handling Python exceptions.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 references

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.

observation · 1
Key points
  • Catch specific exceptions like requests.Timeout.
  • finally always runs for cleanup.
  • Let unexpected exceptions show a traceback.
Key checks
  • 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.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docPython automation runtime current

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%
Depth when you need it

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.

Confirmation

Confirm action

Continue?