← Practical Python
04 / 10 · 23 MIN

Errors and files with context

Handle expected failures and keep resources under control.

Handle the right failure

Catch specific exceptions when you have a defined recovery. An overly broad except can hide programming errors and make a process appear successful. Add useful context without logging passwords, tokens, or sensitive data.

Release resources

Use with when opening files so the resource is closed even if an exception occurs inside the block. Specify text encoding. For external operations, consider timeouts, bounded retries, and the risk of repeating effects that already happened.

Guided workplace application

Distinguish optional from mandatory input before choosing recovery. If a required file is missing, returning empty text may turn delivery failure into a false zero-movement report. Record context and report failure. A with block ensures closure of an opened file but does not roll back earlier writes or validate contents. To publish complete reports only, prepare a temporary file, validate it, and only then replace the destination under supported system conditions. On POSIX, successful os.replace is atomic, and using the same filesystem avoids the cross-filesystem movement limitation. Durability after power failure requires additional analysis. Do not use except Exception: pass as a success policy; identify failures you can recover from and propagate the rest.

Cleanup without hiding the error

A finally block runs during exit, but a return inside it can replace the return value or suppress an exception that should reach the caller. An importer may then receive [] and report success despite a failed read. Avoid using cleanup return as the work result. Python 3.14 emits SyntaxWarning for this pattern; local 3.13 examples demonstrate semantics, not emission of that warning.

Classify errors by operation scope

Restrict try to operations whose failure the handler can interpret. If parsing and publication can both raise ValueError, a handler labeling everything invalid input hides publication errors. An else separates the path after successful parsing, with its own handling where needed. KeyboardInterrupt inherits from BaseException outside Exception: interruption needs deliberate policy. finally may clean up resources during failure or interruption, but cleanup does not establish completion of business work.

from pathlib import Path

try:
 text = Path("required-report.txt").read_text(encoding="utf-8")
except FileNotFoundError as exc:
 raise SystemExit("Required input missing") from exc
IN PRACTICE

An import fails halfway through. Before retrying, check which records committed and whether the operation is idempotent. Logging an error and continuing silently can produce an incomplete report presented as valid.

Common pitfalls

Turning missing mandatory files into empty input; confusing with with rollback; suppressing failures.

Related topics: Precision, external data, and time · Observable and repeatable automation

Take this idea with you

Recovery must be explicit. Closing resources and bounding retries are part of correctness.

Create account

Reference: Python 3.14: Errors and exceptions · Python 3.14; DR Python 2026.3