如何使用 try 检查所有异常,除了在 Python 2.7 中没有 pep8 警告?



我正试图使用tryexcept检查所有可能的错误,但当我使用except Exception as e:时,pep8会说"过于宽泛的例外条款";。我尝试添加logging.exception(e),但现在根本不起作用(我记得导入日志(。

PEP8将遵循标准,编写易于阅读、易于发现错误以及更多内容的代码。PEP 8之所以发出警告,是因为您没有提到任何Exception类型。虽然这是无害的,但根本不是一个好的做法。无论何时处理异常,都应该更加具体,因为这可能有助于缩小错误范围。

示例

def foo():
try:
1/0
except ZeroDivisionError:
print("You can not divide by zero")
except Exception as e:
print("Some unknown error occurred. Error is: " + e.__str__())
def bar():
try:
raise Exception("I am crashed")
except ZeroDivisionError:
print("You can not divide by zero")
except Exception as e:
print("Some unknown error occurred. Error is: " + e.__str__())

if __name__ == '__main__':
foo()
bar()

你明白了。除非没有任何异常类型,否则永远不要写入。

最新更新