Back to the blog

Tony CantaveHow I Handle Errors in Small Python Scripts Without Hiding Bugs

By Tony Cantave ·

When I ran production with ERP and SAP integration, the worst problems were never the ones that stopped the line. A machine that faulted loudly got fixed in minutes. The expensive problems were the quiet ones: a sync job that failed overnight, logged nothing useful, and left inventory counts wrong until someone noticed days later.

I think about that every time I write a try block in Python. Error handling in a small script has one job. When something goes wrong, the script should fail in a way a person can understand and fix quickly. Here are the patterns I actually use.

Catch the narrowest exception you can

The most common mistake I see, and one I made for years, is the bare except:

try:
    stops = int(row["stops"])
except:
    stops = 0

This catches everything, including a typo in a variable name and even the KeyboardInterrupt you get from pressing Ctrl+C. A missing column and a bad number both quietly become zero, and the report looks fine when it is wrong.

Name the exceptions you expect and handle each one on purpose:

def read_stops(row, line_no):
    try:
        return int(row["stops"])
    except KeyError:
        raise SystemExit("Input file has no 'stops' column")
    except ValueError:
        print(f"Line {line_no}: {row['stops']!r} is not a number, using 0")
        return 0

A missing column now stops the script with a clear message. A bad value is handled, but it is also reported, so nobody is surprised later.

Keep the try block small

Only wrap the line that can actually raise the error you are catching.

# Too broad
try:
    data = load(path)
    cleaned = clean(data)
    write_report(cleaned)
except FileNotFoundError:
    print("Input file not found")

If write_report fails because a template file is missing, this message blames the input file and sends you looking in the wrong place. Narrow it:

try:
    data = load(path)
except FileNotFoundError:
    raise SystemExit(f"Input file not found: {path}")

cleaned = clean(data)
write_report(cleaned)

Now any other failure surfaces with its own traceback, pointing at the real line.

Use else and finally for cleanup

Python's try statement has two clauses people often skip:

import sqlite3

conn = sqlite3.connect("runs.db")
try:
    conn.execute("INSERT INTO runs (status) VALUES (?)", ("ok",))
except sqlite3.IntegrityError as err:
    conn.rollback()
    print(f"Insert rejected: {err}")
else:
    conn.commit()
finally:
    conn.close()

The else block runs only when nothing failed, so the commit happens only on success. The finally block always runs, so the connection closes either way. For files, a with block handles the cleanup for you and is usually the cleaner choice.

Add context when you raise again

Sometimes a low level error needs a higher level explanation. Wrap it, and keep the original attached with from:

class ConfigError(Exception):
    pass

def read_port(settings):
    try:
        return int(settings["port"])
    except (KeyError, ValueError) as err:
        raise ConfigError("settings need a whole number 'port' value") from err

The person reading the traceback sees both the plain English message and the original KeyError or ValueError underneath it.

Log the traceback, not just the message

For anything that runs unattended, such as a scheduled job, the log is the only witness. A one line message is rarely enough.

import logging

logging.basicConfig(filename="sync.log", level=logging.INFO)
log = logging.getLogger(__name__)

try:
    sync_inventory()
except Exception:
    log.exception("Inventory sync failed")
    raise

The log.exception call records the full traceback. The bare raise afterward matters just as much: the script still exits with a failure status, so cron or whatever scheduler runs it can notice. Catching the broad Exception class is acceptable here only because nothing is swallowed.

Collect row errors instead of stopping at the first one

When processing a file of records, stopping at the first bad row is frustrating. Fix one line, run it again, hit the next one. I collect the problems and report them together:

errors = []
good = []

for line_no, row in enumerate(rows, start=2):
    try:
        good.append(parse_row(row))
    except ValueError as err:
        errors.append(f"Line {line_no}: {err}")

print(f"{len(good)} rows loaded, {len(errors)} rejected")
for message in errors[:20]:
    print(message)

Starting the count at 2 makes the line numbers match the file when line 1 is a header. Printing only the first twenty keeps a badly broken file from flooding the screen.

Exit with a meaningful status

A script that prints an error but exits with status 0 tells every other tool that it succeeded.

import sys

def main():
    errors = run()
    return 1 if errors else 0

if __name__ == "__main__":
    sys.exit(main())

Zero means success, anything else means something needs attention. Shell scripts, cron and CI systems all rely on that convention.

What AI evaluation taught me about this

Part of my work as an AI evaluator is writing and debugging Python samples and reviewing generated code. One pattern shows up again and again: code that wraps everything in a try block with except Exception and pass. It looks robust because it never crashes. In practice it is the opposite, because every failure becomes invisible. When I score that kind of output, swallowed errors count against it. A script that stops with a clear message is more trustworthy than one that always appears to succeed.

My short checklist

  • Catch specific exceptions, never a bare except.
  • Keep try blocks around only the lines that can fail.
  • Write messages that say what went wrong and where to look.
  • Log full tracebacks for anything that runs unattended.
  • Raise again or exit with a nonzero status so failures are visible.
  • Never write except with pass unless you can explain exactly why in a comment.

None of this takes much code. It just takes deciding, ahead of time, that a failure should be loud and specific. That decision has saved me more hours than any library I have ever installed.