我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。
try:
something
except:
pass
为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?
我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。
try:
something
except:
pass
为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?
当前回答
如果这是糟糕的做法,“通过”就不会是一个选项。 如果你有一个资产,从许多地方接收信息IE一个表单或userInput,它就会派上用场。
variable = False
try:
if request.form['variable'] == '1':
variable = True
except:
pass
其他回答
执行你的伪代码甚至不会给出任何错误:
try:
something
except:
pass
就好像它是一段完全有效的代码,而不是抛出NameError。我希望这不是你想要的。
except:pass构造本质上是在运行try:块中包含的代码时,使出现的任何和所有异常条件保持沉默。
这种糟糕的做法是因为它通常不是你真正想要的。更常见的情况是,出现一些特定的情况,你想要保持沉默,除了:pass是一个太生硬的工具。它将完成工作,但它也会掩盖其他错误条件,您可能没有预料到,但可能非常希望以其他方式处理。
What makes this particularly important in Python is that by the idioms of this language, exceptions are not necessarily errors. They're often used this way, of course, just as in most languages. But Python in particular has occasionally used them to implement an alternative exit path from some code tasks which isn't really part of the normal running case, but is still known to come up from time to time and may even be expected in most cases. SystemExit has already been mentioned as an old example, but the most common example nowadays may be StopIteration. Using exceptions this way caused a lot of controversy, especially when iterators and generators were first introduced to Python, but eventually the idea prevailed.
第一个原因已经说过了——它隐藏了你没有预料到的错误。
(#2)——它使你的代码难以被其他人阅读和理解。如果你捕捉FileNotFoundException当你试图读取一个文件,那么它是相当明显的另一个开发人员'catch'块应该有什么功能。如果您没有指定异常,那么您需要额外的注释来解释该块应该做什么。
(#3) -它演示了惰性编程。如果您使用通用的try/catch,则表明您不了解程序中可能的运行时错误,或者您不知道Python中可能存在哪些异常。捕捉特定的错误表明您了解程序和Python抛出的错误范围。这更有可能使其他开发人员和代码审查人员信任您的工作。
处理错误在编程中是非常重要的。您确实需要向用户展示哪里出了问题。在极少数情况下,您可以忽略这些错误。这是非常糟糕的编程习惯。
我正在构建一个将在数据中心运行的应用程序。它不应该生成任何错误或引发任何异常。我的数据中心有一个网络监控系统,其中包括一个SNMP trap接收器。
try:
main()
except as e:
log(str(e))
send_snmp_trap(str(e))
raise
但是这个加薪不会有任何效果因为它是和任何可能剩下的堆栈的底部。
顺便说一句,这不是万能的灵丹妙药。有一些例外情况是无法被发现的。SNMP不能保证传输。YMMV。