Data files · robustness
Trapping Errors in Scripts: Try, Catch and Clean Up
A script that reads files, calls servers and solves systems of equations will meet failures sooner or later: a file is missing, a network drops, a matrix turns out singular. Trapping an error means intercepting that failure so the script can respond on purpose instead of stopping with a stack trace, or worse, carrying on with bad data. The skill lies in deciding what to catch and what to let through. This page sets out a working approach and ties it to the other scripting tasks in Data and files.
The basic shape
A trap has two parts: a protected block of statements and a handler that runs if one of them fails. When the protected block finishes without a failure the handler is skipped.
try:
A = load_matrix("input.dat")
x = solve(A, b)
except FileNotFoundError:
print("input.dat is missing; check the path")
x = None
except LinAlgError:
print("matrix is singular; try a regularized solve")
x = lstsq_solution(A, b)
Each handler names the failure it expects and does something specific. The pair above treats a missing file and a singular matrix differently, because the right response is different.
Catch narrowly
The most damaging pattern is a handler that catches everything and does nothing. It converts a loud, easily located failure into a quiet wrong answer. If a catch-all is truly needed, for example at the outermost layer of a long batch job, it should log the full error with its trace and then stop or skip that one item deliberately. A good test is to ask whether the handler can name what went wrong. If it cannot, it should not be swallowing the error.
Narrow handlers also document the code. Reading except FileNotFoundError tells the next person which failure the author had in mind.
Cleanup that always runs
Resources such as open files, network connections and temporary directories must be released whether or not the work succeeded. A finally block runs after the protected block in every case, including an error that no handler caught. Many languages also offer a context construct that wraps the same idea: the resource is opened at the start and closed automatically on exit.
conn = open_connection(host)
try:
data = conn.fetch("run7.dat")
finally:
conn.close()
This is the pattern behind safe use of FTP connections and database connections, where a leaked connection counts against a limit on the server.
Retries and fallbacks
Some failures are temporary. A server that times out once may answer the second time. Retry a bounded number of times with a pause that grows, say 1, 2 and 4 seconds, and then fail with a message that says how many attempts were made. Retry only operations that are safe to repeat; asking twice for a listing is harmless, while appending a record to a file twice is not.
A fallback is a second method that runs when the first fails: an iterative solver replaced by a slower, more stable direct method, or a cached result used when a download fails. A fallback should always say that it was used. A result that silently came from the backup route can mislead whoever reads it.
Raising your own errors
Checking inputs early and raising a clear error is part of trapping. If a function needs a square matrix, test for it at the entry and say so, instead of letting a shape mismatch show up three calls deeper with an unrelated message. A message should state what was expected, what was found, and where: expected a square matrix, found 100 × 99.
Logging the outcome
Every handled error should leave a trace in a log: the time, the input that triggered it and the action taken. A log of handled errors shows patterns, such as one file out of fifty failing each night, which no individual message reveals. For the interactive side of finding such faults, see breakpoints in scripts and setting up a debugger session.