问题描述
我正在脚本的顶层编写一个异常子句,我只希望它记录发生的任何错误.烦人的是,PyCharm抱怨我是否抓住了Exception
.
I'm writing an exception clause at the top level of a script, and I just want it to log whatever errors occur. Annoyingly, PyCharm complains if I just catch Exception
.
import logging
logging.basicConfig()
try:
raise RuntimeError('Bad stuff happened.')
except Exception: # <= causes warning: Too broad exception clause
logging.error('Failed.', exc_info=True)
此处理程序有问题吗?如果没有,我该如何告诉PyCharm闭嘴?
Is there something wrong with this handler? If not, how can I tell PyCharm to shut up about it?
推荐答案
来自 Joran 的评论:您可以使用# noinspection PyBroadException
告诉PyCharm您可以使用此异常子句.这是我最初想要的,但是我错过了抑制显示的选项检查在建议菜单中.
From a comment by Joran: you can use # noinspection PyBroadException
to tell PyCharm that you're OK with this exception clause. This is what I was originally looking for, but I missed the option to suppress the inspection in the suggestions menu.
import logging
logging.basicConfig()
# noinspection PyBroadException
try:
raise RuntimeError('Bad stuff happened.')
except Exception:
logging.error('Failed.', exc_info=True)
如果您甚至不想记录该异常,而只是想在不抱怨PyCharm的情况下抑制该异常,则Python 3.4中有一个新功能: contextlib.suppress()
.
If you don't even want to log the exception, and you just want to suppress it without PyCharm complaining, there's a new feature in Python 3.4: contextlib.suppress()
.
import contextlib
with contextlib.suppress(Exception):
raise RuntimeError('Bad stuff happened.')
这等效于此:
try:
raise RuntimeError('Bad stuff happened.')
except Exception:
pass
这篇关于避免“太宽泛的例外条款"; PyCharm中的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!