闭坑指南 · Python#经典错误
异常处理:别吞掉错误
裸 except、过宽的 Exception、静默 pass 会让 bug 藏几周。
异常处理:别吞掉错误
反模式
try:
do_something()
except:
pass
捕获 KeyboardInterrupt / SystemExit 以外的所有异常,日志也没有,生产环境噩梦。
建议
- 捕获具体异常:
ValueError,OSError - 记录日志:
logging.exception("...") - 只在你能恢复时捕获;否则向上抛
finally做清理,别用来吞异常
EAFP vs LBYL
Python 倾向 Easier to Ask Forgiveness than Permission(先 try 再 except),但不必滥用。