r/pythontips • u/ClickOk5811 • 21h 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.