裸 except (E722)
源自 pycodestyle linter。
作用
检查 try
-except
语句中是否存在裸 except
捕获。
为什么这不好?
裸 except
会捕获 BaseException
,其中包括 KeyboardInterrupt
、SystemExit
、Exception
等。捕获 BaseException
可能会使程序难以中断(例如,使用 Ctrl-C),并且可能会掩盖其他问题。
示例
try:
raise KeyboardInterrupt("You probably don't mean to break CTRL-C.")
except:
print("But a bare `except` will ignore keyboard interrupts.")
建议改为
如果实际上需要捕获未知错误,请使用 Exception
,它将捕获常规程序错误,但不会捕获重要的系统异常。
def run_a_function(some_other_fn):
try:
some_other_fn()
except Exception as e:
print(f"How exceptional! {e}")