我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。
try:
something
except:
pass
为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?
我经常在其他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只会让你的程序处于未知状态,在这种状态下它会造成更多的损害。
其他回答
执行你的伪代码甚至不会给出任何错误:
try:
something
except:
pass
就好像它是一段完全有效的代码,而不是抛出NameError。我希望这不是你想要的。
你至少应该使用except Exception:来避免捕获系统异常,如SystemExit或KeyboardInterrupt。这里是文档链接。
一般来说,您应该显式地定义想要捕获的异常,以避免捕获不想要的异常。您应该知道您忽略了哪些异常。
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语句的异常块也可能导致代码,其结构处理特殊类型的异常。
我正在构建一个将在数据中心运行的应用程序。它不应该生成任何错误或引发任何异常。我的数据中心有一个网络监控系统,其中包括一个SNMP trap接收器。
try:
main()
except as e:
log(str(e))
send_snmp_trap(str(e))
raise
但是这个加薪不会有任何效果因为它是和任何可能剩下的堆栈的底部。
顺便说一句,这不是万能的灵丹妙药。有一些例外情况是无法被发现的。SNMP不能保证传输。YMMV。
第一个原因已经说过了——它隐藏了你没有预料到的错误。
(#2)——它使你的代码难以被其他人阅读和理解。如果你捕捉FileNotFoundException当你试图读取一个文件,那么它是相当明显的另一个开发人员'catch'块应该有什么功能。如果您没有指定异常,那么您需要额外的注释来解释该块应该做什么。
(#3) -它演示了惰性编程。如果您使用通用的try/catch,则表明您不了解程序中可能的运行时错误,或者您不知道Python中可能存在哪些异常。捕捉特定的错误表明您了解程序和Python抛出的错误范围。这更有可能使其他开发人员和代码审查人员信任您的工作。