Exceptions Basics
9 examples to get you started with Exceptions - 6 basic and 3 intermediate.
Search across all documentation pages
9 examples to get you started with Exceptions - 6 basic and 3 intermediate.
BaseException; catch Exception in application code, not BaseException.Catch only the failure you can handle.
def parse_port(text: str) -> int:
try:
port = int(text)
except ValueError:
raise ValueError(f"invalid port: {text!r}") from None
return portfrom None suppresses the original chain when it adds noise.Related: Raising & Chaining - preserve tracebacks
Run code only when no exception occurred in try.
def load_config(path: str) -> dict:
try:
f = open(path, encoding="utf-8")
except FileNotFoundError:
return {}
else:
with f:
import json
return json.load(f)else avoids running success-only code inside try (which would catch its exceptions too).except focused on the open failure mode.with when the resource should close on success path.Related: The logging Module - log missing config paths
Cleanup executes whether or not an exception fired.
lock_acquired = False
try:
lock_acquired = True # pretend acquire
print("critical section")
finally:
if lock_acquired:
print("release lock")finally is for release/cleanup guarantees.finally - it overrides try/except returns.with when the object supports context management.Related: Context Managers as a Pattern - structured cleanup
Catch a base class to handle a family of errors.
try:
int("not-a-number")
except (ValueError, TypeError) as exc:
print(type(exc).__name__, exc)OSError subclasses).except catches multiple types.except blocks.Related: Custom Exception Hierarchies - domain bases
Preserve the original traceback inside an except block.
def process():
try:
risky()
except ValueError:
log("bad value") # pretend log
raiseraise re-propagates the active exception with stack intact.raise exc with a stored variable unless you understand traceback binding.Related: Raising & Chaining -
raise ... from
Many exceptions carry structured fields.
try:
open("/no/such/file.txt")
except FileNotFoundError as exc:
print(exc.errno, exc.filename)OSError subclasses expose .errno, .filename, .strerror.Related: Custom Exception Hierarchies - design fields
Returning true from __exit__ suppresses exceptions (rare - use deliberately).
from contextlib import suppress
with suppress(FileNotFoundError):
print(open("optional.txt").read())
print("continues")contextlib.suppress documents intentional swallowing.except: pass in application code.Related: Errors & Logging Best Practices - never swallow silently
Multiple errors can surface as one ExceptionGroup (3.11+).
def failing_tasks():
raise ExceptionGroup(
"batch failed",
[ValueError("a"), TypeError("b")],
)
try:
failing_tasks()
except* ValueError as eg:
print("value errors:", len(eg.exceptions))except* handles matching sub-exceptions inside a group.except* semantics.Related: Exception Groups & except* - full guide
Record context, then fail - do not swallow.
import logging
log = logging.getLogger(__name__)
def charge(amount: float) -> None:
if amount < 0:
log.error("invalid charge amount=%s", amount)
raise ValueError("amount must be non-negative")amount=%s) not f-strings in logging calls.Related: Structured & Contextual Logging - JSON fields
Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026