我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。

try:
    something
except:
    pass

为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?


当前回答

通常,您可以将任何错误/异常分为以下三类之一:

Fatal: Not your fault, you cannot prevent them, you cannot recover from them. You should certainly not ignore them and continue, and leave your program in an unknown state. Just let the error terminate your program, there is nothing you can do. Boneheaded: Your own fault, most likely due to an oversight, bug or programming error. You should fix the bug. Again, you should most certainly not ignore and continue. Exogenous: You can expect these errors in exceptional situations, such as file not found or connection terminated. You should explicitly handle these errors, and only these.

在除了:pass之外的所有情况下,pass只会让你的程序处于未知状态,在这种状态下它会造成更多的损害。

其他回答

>>> import this

The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

所以,这是我的观点。每当你发现一个错误,你应该做一些事情来处理它,即把它写在日志文件或其他东西。至少,它告诉您曾经有一个错误。

执行你的伪代码甚至不会给出任何错误:

try:
    something
except:
    pass

就好像它是一段完全有效的代码,而不是抛出NameError。我希望这不是你想要的。

你至少应该使用except Exception:来避免捕获系统异常,如SystemExit或KeyboardInterrupt。这里是文档链接。

一般来说,您应该显式地定义想要捕获的异常,以避免捕获不想要的异常。您应该知道您忽略了哪些异常。

到目前为止提出的所有意见都是有效的。在可能的情况下,您需要指定想要忽略的异常。在可能的情况下,你需要分析导致异常的原因,只忽略你想要忽略的部分,而不是其他部分。如果异常导致应用程序“壮观地崩溃”,那么就这样吧,因为知道意外发生的时间比隐藏问题发生的时间要重要得多。

综上所述,不要将任何编程实践视为至高无上的。这太愚蠢了。总有时间和地点可以执行“忽略所有异常”块。

白痴派拉特的另一个例子是goto运算符的使用。当我还在学校的时候,我们的教授教我们去运算符,只是为了提醒我们永远不能使用它。不要相信人们告诉你xyz永远不应该被使用,也不可能有一个场景它是有用的。总是有的。

这里的主要问题是它忽略所有和任何错误:内存不足,CPU正在燃烧,用户想要停止,程序想要退出,Jabberwocky正在杀死用户。

这太过分了。在你的脑海中,你在想“我想忽略这个网络错误”。如果出现了意想不到的错误,那么您的代码将继续以完全不可预测的方式中断,没有人可以调试。

这就是为什么您应该限制自己只忽略一些错误,而让其余的错误过去。