我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。
try:
something
except:
pass
为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?
我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。
try:
something
except:
pass
为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?
当前回答
我个人更喜欢这个解决方案:
except ValueError as error:
print(error.args)
pass
错误。Args给了我一个简单的代码行,它不会太分散人的注意力,但确实有助于代码审查,特别是如果错误有不同的原因,比如
(ValueError('year 0 is out of range'),)
(ValueError('month must be in 1..12'),)
(ValueError('day is out of range for month'),)
当研究熊猫的时间周期时。
其他回答
到目前为止提出的所有意见都是有效的。在可能的情况下,您需要指定想要忽略的异常。在可能的情况下,你需要分析导致异常的原因,只忽略你想要忽略的部分,而不是其他部分。如果异常导致应用程序“壮观地崩溃”,那么就这样吧,因为知道意外发生的时间比隐藏问题发生的时间要重要得多。
综上所述,不要将任何编程实践视为至高无上的。这太愚蠢了。总有时间和地点可以执行“忽略所有异常”块。
白痴派拉特的另一个例子是goto运算符的使用。当我还在学校的时候,我们的教授教我们去运算符,只是为了提醒我们永远不能使用它。不要相信人们告诉你xyz永远不应该被使用,也不可能有一个场景它是有用的。总是有的。
处理错误在编程中是非常重要的。您确实需要向用户展示哪里出了问题。在极少数情况下,您可以忽略这些错误。这是非常糟糕的编程习惯。
通常,您可以将任何错误/异常分为以下三类之一:
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只会让你的程序处于未知状态,在这种状态下它会造成更多的损害。
In my opinion errors have a reason to appear, that my sound stupid, but thats the way it is. Good programming only raises errors when you have to handle them. Also, as i read some time ago, "the pass-Statement is a Statement that Shows code will be inserted later", so if you want to have an empty except-statement feel free to do so, but for a good program there will be a part missing. because you dont handle the things you should have. Appearing exceptions give you the chance to correct input data or to change your data structure so these exceptions dont occur again (but in most cases (Network-exceptions, General input-exceptions) exceptions indicate that the next parts of the program wont execute well. For example a NetworkException can indicate a broken network-connection and the program cant send/recieve data in the next program steps.
但是只对一个执行块使用pass块是有效的,因为你仍然可以区分不同类型的异常,所以如果你把所有的异常块放在一个中,它就不是空的:
try:
#code here
except Error1:
#exception handle1
except Error2:
#exception handle2
#and so on
可以写成这样:
try:
#code here
except BaseException as e:
if isinstance(e, Error1):
#exception handle1
elif isinstance(e, Error2):
#exception handle2
...
else:
raise
因此,即使是多个带有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!
所以,这是我的观点。每当你发现一个错误,你应该做一些事情来处理它,即把它写在日志文件或其他东西。至少,它告诉您曾经有一个错误。