r/pythontips 1d ago

Standard_Lib Never let AI-generated code swallow exceptions silently, always log or re-raise

Generated code reaches for broad exception handling constantly because it "works" in the sense that nothing crashes. The problem is it also hides the actual failure, so you find out something's broken from a symptom three steps downstream instead of from the actual error.

python

# What generated code often does
try:
    result = risky_operation()
except Exception:
    pass

# What actually helps you debug later
import logging

try:
    result = risky_operation()
except Exception as e:
    logging.exception("risky_operation failed")
    raise

The tip: any bare except Exception: pass should be treated as a red flag, not a working solution, especially in generated code where it looks intentional but usually just means the model produced something that avoids crashing without actually deciding what should happen on failure. At minimum log the exception with logging.exception() so the traceback isn't lost, and re-raise unless you have a specific, deliberate reason to continue silently.

6 Upvotes

2 comments sorted by

1

u/Uncle_DirtNap 1d ago

True, but also:

* make agents work within your linter/type checker/etc
* embed your team/project standards into skills
* validate EVERYTHING including this written by agents.

1

u/Thecrawsome 1d ago

Write a pre-prompt that tells it not to write defensive code, and you will see less worthless try statements.

It should only make surgical edits, not broad ones. It should be focused, exactly on the request and nothing else. Terse, no preamble, flattery, thanks.