One-Line Definition
Exception handling propagates a failure from the point where it occurs up to a layer that has enough context to decide what to do next—using explicit exception types, cause chains, and deterministic cleanup logic to support error reporting, retries, or graceful fallback.
Why It Matters
- Production environments are full of unexpected failures: Missing files, network timeouts, HTTP 429 rate limits, and malformed user inputs happen constantly. Without structured exception handling, a program crashes on its first encounter with real-world noise.
- Bad error handling is more dangerous than no error handling: Silently swallowing exceptions lets corrupted state propagate quietly until the application fails far away from the true root cause.
- A defining line between fragile scripts and maintainable systems: Well-designed exception hierarchies let callers see immediately what can go wrong and how to recover.
Operating Boundaries
A finally block executes during normal stack unwinding, but cannot run if the OS forcefully kills the process (e.g., SIGKILL) or power is lost. Retrying failed calls also requires checking idempotency, retry budgets, and server backoff headers—and a client-side timeout never guarantees that the remote side did not complete the write.
How It Works / Diagram
Official Python tutorial on Errors and Exceptions: https://docs.python.org/3/tutorial/errors.html; built-in exception hierarchy: https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Five core habits for clean exception handling:
| # | Habit | Why It Helps |
|---|---|---|
| 1 | Define domain-specific custom exceptions | Callers can catch ConfigError precisely instead of guessing which ValueError came from where |
| 2 | Keep the try block as small as possible |
Wrap only the exact statement that may fail so you don't accidentally mask bugs in surrounding lines |
| 3 | Catch specific exception subclasses | A bare except: catches even KeyboardInterrupt and SystemExit |
| 4 | Use finally or with for cleanup |
Guarantees scheduled resource cleanup on both normal exit and stack unwinding (see k1.py.context-manager) |
| 5 | Handle errors at the layer that knows how to recover | Low-level helpers raise informative exceptions; higher-level orchestrators decide whether to retry, degrade, or surface an error to the user |
Python 3.11 introduced ExceptionGroup and except* (PEP 654) to handle multiple exceptions raised concurrently—for example, when several sub-tasks inside an async task group fail during the same turn: https://peps.python.org/pep-0654/
Runnable Example
# File: examples/16_exceptions.py
# Five good habits of exception handling
import json, logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("demo")
class ConfigError(Exception):
"""1) Custom domain exception: allows callers to catch config failures precisely"""
def read_port(cfg: dict) -> int:
try:
port = int(cfg["port"]) # 2) Keep the try block minimal
except KeyError:
raise ConfigError("Missing 'port' configuration") from None
except (TypeError, ValueError) as e: # 3) Catch specific exceptions, never bare except
raise ConfigError(f"'port' is not an integer: {cfg['port']!r}") from e
else:
if not 0 < port < 65536:
raise ConfigError(f"'port' out of valid range: {port}")
return port
finally:
log.info("read_port check finished") # 4) Use finally for cleanup / completion logging
for cfg in [{"port": "8080"}, {}, {"port": "abc"}, {"port": 70000}]:
try:
print("Port =", read_port(cfg))
except ConfigError as e:
log.warning("Config error: %s", e) # 5) Handle and log at the appropriate boundary
# Python 3.11+: ExceptionGroup and except* for multiple concurrent failures
try:
raise ExceptionGroup("Batch validation failed", [ValueError("Field A is empty"), TypeError("Field B has wrong type")])
except* ValueError as eg:
print("Handled ValueErrors:", [str(e) for e in eg.exceptions])
except* TypeError as eg:
print("Handled TypeErrors:", [str(e) for e in eg.exceptions])
Recorded output (Python 3.15.0):
INFO read_port check finished
INFO read_port check finished
WARNING Config error: Missing 'port' configuration
INFO read_port check finished
WARNING Config error: 'port' is not an integer: 'abc'
INFO read_port check finished
WARNING Config error: 'port' out of valid range: 70000
Port = 8080
Handled ValueErrors: ['Field A is empty']
Handled TypeErrors: ['Field B has wrong type']
Key observations from the output:
- The
finallyblock ran on every single invocation (four"read_port check finished"log lines). - For
{"port": "abc"},raise ... from echained the originalValueErroras the explicit__cause__. except*partitioned theExceptionGroupby exception type and handled both subgroups cleanly.
Common Pitfalls
except Exception: pass: The single most common and dangerous anti-pattern. At a minimum, log the failure; better yet, catch only the specific exception subclass you know how to recover from.- Using exceptions for ordinary control flow: Avoid replacing simple
ifchecks with exceptions (the iterator protocol'sStopIterationis a language-level special case). That said, Python idiomatic style embraces EAFP ("Easier to Ask for Forgiveness than Permission"), such astry: val = d[k] except KeyError:, when key misses are rare. See the EAFP glossary entry: https://docs.python.org/3/glossary.html#term-EAFP - Losing the original traceback when wrapping exceptions: Always write
raise NewError(...) from e(orfrom Nonewhen intentionally hiding internal implementation noise). - Using
returninside afinallyblock: Areturninfinallysilently discards any active exception currently unwinding the stack. Starting in Python 3.14,return,break, andcontinueinsidefinallyemit aSyntaxWarning(PEP 765): https://peps.python.org/pep-0765/
Relevance to AI Engineering
- Failure modes every LLM API client must handle: Network timeouts, rate limits (
HTTP 429), upstream server errors (5xx), safety-filter refusals, and malformed output payloads. The standard pattern is to apply bounded exponential-backoff retries to transient errors (timeouts, 429s, select 5xx responses; see the retry decorator in k1.py.decorator) while failing immediately on non-retryable errors (authentication failures, invalid parameters). - Structured-output parsing failures: Even with schema constraints, models occasionally emit truncated or invalid JSON. Catch
json.JSONDecodeErroror Pydantic'sValidationErrorexplicitly and decide whether to feed the validation error back to the model for a self-correction turn. - Concurrent fan-out failures: When fanning out parallel tool or sub-agent calls inside
asyncio.TaskGroup, multiple failures surface as anExceptionGrouprequiringexcept*(see k1.py.async-await). - A frequent flaw in AI-generated code: Coding agents often wrap large functions in
try/except Exceptionand return a plausible-looking fallback value, masking real bugs. Always scrutinizeexceptblocks during code review.
Further Reading
- Python Tutorial – Errors and Exceptions: https://docs.python.org/3/tutorial/errors.html
- Built-in Exceptions Reference: https://docs.python.org/3/library/exceptions.html
- PEP 654 – Exception Groups and
except*: https://peps.python.org/pep-0654/ - PEP 765 – Disallow
return/break/continuethat exit afinallyblock: https://peps.python.org/pep-0765/
Concept Check
If a network request times out and your client immediately retries a write operation, what can go wrong?
Reference answer: The first request may have already succeeded on the server while only the response packet was lost; if the write operation is not idempotent (for example, lacking an idempotency key), retrying can create a duplicate record or double charge.
Verification & Reproduction
Verified on: 2026-10-14. Example status: Passed. Execution log: 16_exceptions.py.
Companion Code & Verification Materials