我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。
try:
something
except:
pass
为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?
我经常在其他Stack Overflow问题上看到关于如何不鼓励使用except: pass的评论。这为什么不好呢?有时我不在乎错误是什么,我只想继续写代码。
try:
something
except:
pass
为什么使用except: pass块不好?是什么让它变得糟糕?是我传递了一个错误还是我排除了任何错误?
当前回答
因为它还没有被提及,所以使用contextlib.suppress是更好的风格:
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
在本例中,somefile.tmp在执行此代码块后将不存在,而不会引发任何异常(除了FileNotFoundError,它被抑制)。
其他回答
第一个原因已经说过了——它隐藏了你没有预料到的错误。
(#2)——它使你的代码难以被其他人阅读和理解。如果你捕捉FileNotFoundException当你试图读取一个文件,那么它是相当明显的另一个开发人员'catch'块应该有什么功能。如果您没有指定异常,那么您需要额外的注释来解释该块应该做什么。
(#3) -它演示了惰性编程。如果您使用通用的try/catch,则表明您不了解程序中可能的运行时错误,或者您不知道Python中可能存在哪些异常。捕捉特定的错误表明您了解程序和Python抛出的错误范围。这更有可能使其他开发人员和代码审查人员信任您的工作。
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.
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语句的异常块也可能导致代码,其结构处理特殊类型的异常。
简单地说,如果抛出异常或错误,就说明出了问题。这可能不是什么非常错误的事情,但是仅仅为了使用goto语句而创建、抛出和捕获错误和异常并不是一个好主意,而且很少这样做。99%的情况下,都是某个地方出了问题。
问题需要处理。就像在生活中一样,在编程中,如果你把问题放在一边,试着忽略它们,很多时候它们不会自己消失;相反,它们变得越来越大,越来越多。为了防止一个问题在你身上滋生,并在将来再次出现,你要么1)消除它,然后清理混乱,要么2)控制它,然后清理混乱。
忽略异常和错误并让它们保持原样是体验内存泄漏、未完成的数据库连接、不必要的文件权限锁定等的好方法。
在极少数情况下,这个问题是如此微不足道,微不足道,而且——除了需要尝试……Catch block - self-contained,这样就真的没有什么乱七八糟的东西需要清理了。只有在这些情况下,这种最佳实践并不一定适用。根据我的经验,这通常意味着无论代码在做什么,基本上都是微不足道的,可以忽略的,而像重试尝试或特殊消息这样的事情既不值得复杂,也不值得暂停线程。
在我的公司,规则是几乎总是在catch块中做一些事情,如果你什么都不做,那么你必须总是放置一个注释,并给出一个很好的理由。当有事情要做的时候,你绝对不能错过或留下一个空的catch块。
首先,它违背了Python的两个禅宗原则:
显性比隐性好 错误绝不能悄无声息地过去
它的意思是,你故意让你的错误悄无声息地过去。此外,您不知道究竟发生了哪个错误,因为except: pass将捕获任何异常。
其次,如果我们试图从Python的禅意中抽象出来,而只是从理智的角度来说话,你应该知道,使用except:pass会让你在系统中失去知识和控制。经验法则是,如果发生错误,就引发异常,并采取适当的操作。如果你事先不知道这些操作应该是什么,至少在某个地方记录错误(最好重新引发异常):
try:
something
except:
logger.exception('Something happened')
但是,通常情况下,如果您试图捕获任何异常,那么您可能正在做错误的事情!