Python 在 PyCharm 中避免“太广泛的例外条款”警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40775709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Avoiding "Too broad exception clause" warning in PyCharm
提问by Don Kirkby
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
.
我正在脚本的顶层编写一个异常子句,我只希望它记录发生的任何错误。烦人的是,PyCharm 会抱怨我是否只是抓住了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)
Is there something wrong with this handler? If not, how can I tell PyCharm to shut up about it?
这个处理程序有问题吗?如果没有,我怎么能告诉 PyCharm 闭嘴呢?
回答by Don Kirkby
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 inspectionin the suggestions menu.
来自Joran的评论:你可以# noinspection PyBroadException
用来告诉 PyCharm 你对这个例外条款没问题。这就是我最初要寻找的,但我错过了在建议菜单中取消检查的选项。
import logging
logging.basicConfig()
# noinspection PyBroadException
try:
raise RuntimeError('Bad stuff happened.')
except Exception:
logging.error('Failed.', exc_info=True)
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()
.
如果您甚至不想记录异常,而只想在 PyCharm 不抱怨的情况下抑制它,那么 Python 3.4 中有一个新功能:contextlib.suppress()
.
import contextlib
with contextlib.suppress(Exception):
raise RuntimeError('Bad stuff happened.')
That's equivalent to this:
这相当于:
try:
raise RuntimeError('Bad stuff happened.')
except Exception:
pass
回答by DeanM
I am reluctant to turn off warnings as a matter of principle.
原则上我不愿意关闭警告。
In the case presented, you know well what the exception is. It might be best to just be specific. For example:
在所呈现的案例中,您很清楚异常是什么。最好是具体的。例如:
try: raise RuntimeError("Oops") except RuntimeError as e: print(e, "was handled")
will yield "Oops was handled".
try: raise RuntimeError("Oops") except RuntimeError as e: print(e, "was handled")
将产生“哎呀已处理”。
If there are a couple of possible exceptions, you could use two except clauses. If there could be a multitude of possible exceptions, should one attempt to use a single try-block to handle everything? It might be better to reconsider the design!
如果有几个可能的例外,您可以使用两个 except 子句。如果可能存在多种可能的异常,是否应该尝试使用单个 try 块来处理所有内容?重新考虑设计可能会更好!
回答by Don Kirkby
I found a hint in this closed feature requestfor PyCharm:
我在PyCharm 的这个关闭功能请求中找到了一个提示:
I suggest you to mark this inspection as 'okay' if the except block makes use of exception instance
e
somehow.
如果 except 块
e
以某种方式使用异常实例,我建议您将此检查标记为“正常” 。
Because I'm logging with exc_info=True
, I'm implicitly using the current exception object, but PyCharm doesn't know that. To make it explicit, I can pass the exception object to exc_info
. Since Python 3.5, the logger methodshave accepted an exception instance to report, as well as accepting any truthy value to report the current exception and stack trace in the log.
因为我使用 登录exc_info=True
,所以我隐式地使用了当前的异常对象,但 PyCharm 不知道这一点。为了明确起见,我可以将异常对象传递给exc_info
. 从 Python 3.5 开始,记录器方法接受了要报告的异常实例,并接受任何真实值来报告日志中的当前异常和堆栈跟踪。
import logging
logging.basicConfig()
try:
raise RuntimeError('Bad stuff happened.')
except Exception as e:
logging.error('Failed.', exc_info=e)
回答by daniel_serretti
Not sure about your PyCharm version (mine is 2019.2), but I strongly recommend disabling this PyCharm inspection in File> Settings> Editor> Inspections and type "too broad". In Python tab, deselect "too broad exceptions clauses" to avoid those. I believe this way PyCharm would show you the correct expression inspection
不确定您的 PyCharm 版本(我的是 2019.2),但我强烈建议在“文件”>“设置”>“编辑器”>“检查”中禁用此 PyCharm 检查并键入“太宽泛”。在 Python 选项卡中,取消选择“过于广泛的例外条款”以避免这些。我相信这样 PyCharm 会向您展示正确的表达式检查