采用try-except语句时,应该尽可能精确地指明需要捕获的异常类型,而不是使用过于普遍的Exception异常类型。这样可以保证只有应该捕获的异常被处理,避免捕获一些无关紧要的异常,或者隐藏代码中的潜在问题。
例如,下面的代码中,使用了过于普遍的Exception异常类型来捕获所有可能发生的异常:
try:
# some code
except Exception: # 过于普遍的Exception异常类型
# handle the exception
应该将其改为精确指定需要捕获的异常类型,例如:
try:
# some code
except ValueError: # 指定捕获ValueError类型的异常
# handle the exception
except FileNotFoundError: # 指定捕获FileNotFoundError类型的异常
# handle the exception