Python 为什么“except: pass”是一种糟糕的编程习惯?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21553327/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is "except: pass" a bad programming practice?
提问by Vader
I often see comments on other Stack Overflow questions about how the use of except: passis discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code.
我经常看到关于其他 Stack Overflow 问题的评论,关于如何except: pass不鼓励使用。为什么这很糟糕?有时我只是不在乎错误是什么,我只想继续代码。
try:
    something
except:
    pass
Why is using an except: passblock bad? What makes it bad? Is it the fact that I passon an error or that I exceptany error?
为什么使用except: pass块不好?是什么让它变得糟糕?是我pass犯了错误还是我有except任何错误?
采纳答案by poke
As you correctly guessed, there are two sides to it: Catching anyerror by specifying no exception type after except, and simply passing it without taking any action.
正如您正确猜到的那样,它有两个方面:通过在 之后不指定异常类型来捕获任何错误except,以及简单地传递它而不采取任何行动。
My explanation is “a bit” longer—so tl;dr it breaks down to this:
我的解释“有点”更长——所以 tl;dr 它分解为:
- Don't catch anyerror. Always specify which exceptions you are prepared to recover from and only catch those.
 - Try to avoid passing in except blocks. Unless explicitly desired, this is usually not a good sign.
 
- 不要发现任何错误。始终指定您准备从哪些异常中恢复并且只捕获那些异常。
 - 尽量避免传入 except blocks。除非明确要求,否则这通常不是一个好兆头。
 
But let's go into detail:
但让我们详细介绍一下:
Don't catch anyerror
不要捕捉任何错误
When using a tryblock, you usually do this because you know that there is a chance of an exception being thrown. As such, you also already have an approximate idea of whatcan break and what exception can be thrown. In such cases, you catch an exception because you can positively recoverfrom it. That means that you are prepared for the exception and have some alternative plan which you will follow in case of that exception.
使用try块时,您通常会这样做,因为您知道有可能抛出异常。因此,您也已经大致了解什么可以中断以及可以抛出什么异常。在这种情况下,您可以捕获异常,因为您可以积极地从中恢复。这意味着您已为例外做好了准备,并有一些替代计划,您将在发生该例外时遵循该计划。
For example, when you ask for the user to input a number, you can convert the input using int()which might raise a ValueError. You can easily recover that by simply asking the user to try it again, so catching the ValueErrorand prompting the user again would be an appropriate plan. A different example would be if you want to read some configuration from a file, and that file happens to not exist. Because it is a configuration file, you might have some default configuration as a fallback, so the file is not exactly necessary. So catching a FileNotFoundErrorand simply applying the default configuration would be a good plan here. Now in both these cases, we have a very specific exception we expect and have an equally specific plan to recover from it. As such, in each case, we explicitly only exceptthat certainexception.
例如,当您要求用户输入一个数字时,您可以使用int()which 可能会引发ValueError. 您可以通过简单地要求用户再次尝试来轻松恢复,因此捕获ValueError并再次提示用户将是一个合适的计划。另一个例子是,如果您想从文件中读取一些配置,而该文件恰好不存在。因为它是一个配置文件,您可能有一些默认配置作为后备,因此该文件并不是必需的。因此,在这里捕获一个FileNotFoundError并简单地应用默认配置将是一个很好的计划。现在,在这两种情况下,我们都有一个非常具体的例外,我们期望并有一个同样具体的计划来从中恢复。因此,在每种情况下,我们只明确except某些例外。
However, if we were to catch everything, then—in addition to those exceptions we are prepared to recover from—there is also a chance that we get exceptions that we didn't expect, and which we indeed cannot recover from; or shouldn't recover from.
但是,如果我们要捕获所有内容,那么——除了我们准备从中恢复的那些异常之外——还有可能我们得到我们没有预料到的异常,并且我们确实无法从中恢复;或不应该从中恢复。
Let's take the configuration file example from above. In case of a missing file, we just applied our default configuration, and might decided at a later point to automatically save the configuration (so next time, the file exists). Now imagine we get a IsADirectoryError, or a PermissionErrorinstead. In such cases, we probably do not want to continue; we could still apply our default configuration, but we later won't be able to save the file. And it's likely that the user meant to have a custom configuration too, so using the default values is likely not desired. So we would want to tell the user about it immediately, and probably abort the program execution too. But that's not something we want to do somewhere deep within some small code part; this is something of application-level importance, so it should be handled at the top—so let the exception bubble up.
让我们以上面的配置文件为例。如果缺少文件,我们只是应用了我们的默认配置,并且可能会在稍后决定自动保存配置(因此下次该文件存在)。现在想象我们得到一个IsADirectoryError,或者一个PermissionError反而。在这种情况下,我们可能不想继续;我们仍然可以应用我们的默认配置,但我们稍后将无法保存文件。并且用户很可能也打算拥有自定义配置,因此可能不希望使用默认值。所以我们想立即告诉用户它,并且可能也中止程序执行。但这不是我们想要在某个小代码部分深处做的事情;这是应用程序级的重要性,所以它应该在顶部处理——所以让异常冒泡。
Another simple example is also mentioned in the Python 2 idiomsdocument. Here, a simple typo exists in the code which causes it to break. Because we are catching everyexception, we also catch NameErrorsand SyntaxErrors. Both are mistakes that happen to us all while programming; and both are mistakes we absolutely don't want to include when shipping the code. But because we also caught those, we won't even know that they occurred there and lose any help to debug it correctly.
Python 2 idioms文档中也提到了另一个简单的例子。在这里,代码中存在一个简单的拼写错误,导致代码中断。因为我们正在捕获每个异常,所以我们也捕获了NameErrors和SyntaxErrors。两者都是我们在编程时都会发生的错误;并且这两个错误都是我们在发送代码时绝对不想包含的错误。但是因为我们也捕捉到了这些,我们甚至不会知道它们发生在那里并且失去了正确调试它的任何帮助。
But there are also more dangerous exceptions which we are unlikely prepared for. For example SystemErroris usually something that happens rarely and which we cannot really plan for; it means there is something more complicated going on, something that likely prevents us from continuing the current task.
但也有更危险的例外情况,我们不太可能为此做好准备。例如SystemError通常很少发生并且我们无法真正计划;这意味着有一些更复杂的事情正在发生,可能会阻止我们继续当前的任务。
In any case, it's very unlikely that you are prepared for everything in a small scale part of the code, so that's really where you should only catch those exceptions you are prepared for. Some people suggest to at least catch Exceptionas it won't include things like SystemExitand KeyboardInterruptwhich by designare to terminate your application, but I would argue that this is still far too unspecific. There is only one place where I personally accept catching Exceptionor just anyexception, and that is in a single global application-level exception handler which has the single purpose to log any exception we were not prepared for. That way, we can still retain as much information about unexpected exceptions, which we then can use to extend our code to handle those explicitly (if we can recover from them) or—in case of a bug—to create test cases to make sure it won't happen again. But of course, that only works if we only ever caught those exceptions we were already expecting, so the ones we didn't expect will naturally bubble up.
在任何情况下,您都不太可能在代码的一小部分中为所有内容做好准备,因此实际上您应该只捕获那些您准备好的异常。有些人建议至少 catch ,Exception因为它不会包含诸如SystemExit和KeyboardInterrupt哪些设计会终止您的应用程序之类的内容,但我认为这仍然太不具体了。只有一个地方我个人接受捕捉Exception或任何一个异常,这是在一个单一的全局应用程序级异常处理程序中,它的唯一目的是记录我们没有准备好的任何异常。这样,我们仍然可以保留尽可能多的关于意外异常的信息,然后我们可以使用这些信息来扩展我们的代码以显式处理这些异常(如果我们可以从它们中恢复)或者 - 在出现错误的情况下 - 创建测试用例以确保它不会再发生了。但是,当然,这只有在我们只捕捉到那些我们已经预料到的异常时才有效,所以我们没有预料到的异常会自然而然地冒出来。
Try to avoid passing in except blocks
尽量避免传入除了块
When explicitly catching a small selection of specific exceptions, there are many situations in which we will be fine by simply doing nothing. In such cases, just having except SomeSpecificException: passis just fine. Most of the time though, this is not the case as we likely need some code related to the recovery process (as mentioned above). This can be for example something that retries the action again, or to set up a default value instead.
当显式捕获一小部分特定异常时,在许多情况下,我们只需什么都不做就可以了。在这种情况下,拥有except SomeSpecificException: pass就好了。但大多数情况下,情况并非如此,因为我们可能需要一些与恢复过程相关的代码(如上所述)。例如,这可以是再次重试操作的内容,或者改为设置默认值。
If that's not the case though, for example because our code is already structured to repeat until it succeeds, then just passing is good enough. Taking our example from above, we might want to ask the user to enter a number. Because we know that users like to not do what we ask them for, we might just put it into a loop in the first place, so it could look like this:
如果情况并非如此,例如因为我们的代码已经被构造为重复直到成功,那么仅仅通过就足够了。以上面的例子为例,我们可能想要求用户输入一个数字。因为我们知道用户不喜欢我们要求他们做的事情,所以我们可能首先将其放入循环中,因此它可能如下所示:
def askForNumber ():
    while True:
        try:
            return int(input('Please enter a number: '))
        except ValueError:
            pass
Because we keep trying until no exception is thrown, we don't need to do anything special in the except block, so this is fine. But of course, one might argue that we at least want to show the user some error message to tell him why he has to repeat the input.
因为我们一直尝试直到没有异常抛出,所以我们不需要在 except 块中做任何特殊的事情,所以这很好。但当然,有人可能会争辩说,我们至少要向用户显示一些错误消息,告诉他为什么必须重复输入。
In many other cases though, just passing in an exceptis a sign that we weren't really prepared for the exception we are catching. Unless those exceptions are simple (like ValueErroror TypeError), and the reason why we can pass is obvious, try to avoid just passing. If there's really nothing to do (and you are absolutely sure about it), then consider adding a comment why that's the case; otherwise, expand the except block to actually include some recovery code.
但在许多其他情况下,仅仅传入 anexcept就表明我们并没有真正为我们捕获的异常做好准备。除非这些异常很简单(比如ValueError或TypeError),并且我们可以通过的原因很明显,否则尽量避免只是通过。如果真的无事可做(并且您对此非常确定),请考虑添加评论,为什么会这样;否则,扩展 except 块以实际包含一些恢复代码。
except: pass
except: pass
The worst offender though is the combination of both. This means that we are willingly catching anyerror although we are absolutely not prepared for it andwe also don't do anything about it. You at leastwant to log the error and also likely reraise it to still terminate the application (it's unlikely you can continue like normal after a MemoryError). Just passing though will not only keep the application somewhat alive (depending where you catch of course), but also throw away all the information, making it impossible to discover the error—which is especially true if you are not the one discovering it.
最严重的罪犯是两者的结合。这意味着我们愿意捕捉任何错误,尽管我们绝对没有为此做好准备,而且我们也没有做任何事情。您至少希望记录错误并可能重新引发它以仍然终止应用程序(在 MemoryError 之后您不太可能像往常一样继续)。只是通过不仅会使应用程序保持一定的活力(当然取决于您捕获的位置),而且还会丢弃所有信息,从而无法发现错误 - 如果您不是发现错误的人,则尤其如此。
So the bottom line is: Catch only exceptions you really expect and are prepared to recover from; all others are likely either mistakes you should fix, or something you are not prepared for anyway. Passing specificexceptions is fine if you really don't need to do something about them. In all other cases, it's just a sign of presumption and being lazy. And you definitely want to fix that.
所以底线是:只捕获您真正期望并准备从中恢复的异常;所有其他人可能要么是您应该修复的错误,要么是您无论如何都没有准备好。如果你真的不需要对它们做些什么,传递特定的异常是可以的。在所有其他情况下,这只是一种假设和懒惰的表现。你肯定想解决这个问题。
回答by YS-L
Executing your pseudo code literallydoes not even give any error:
从字面上执行你的伪代码甚至不会给出任何错误:
try:
    something
except:
    pass
as if it is a perfectly valid piece of code, instead of throwing a NameError. I hope this is not what you want.
就好像它是一段完全有效的代码一样,而不是抛出一个NameError. 我希望这不是你想要的。
回答by Tupteq
You should use at least except Exception:to avoid catching system exceptions like SystemExitor KeyboardInterrupt. Here's linkto docs.
您应该至少使用except Exception:以避免捕获系统异常,例如SystemExit或KeyboardInterrupt。这是文档的链接。
In general you should define explicitly exceptions you want to catch, to avoid catching unwanted exceptions. You should know what exceptions you ignore.
通常,您应该明确定义要捕获的异常,以避免捕获不需要的异常。您应该知道您忽略了哪些异常。
回答by Alexander Zhukov
First, it violates two principles of Zen of Python:
首先,它违反了 Python Zen 的两个原则:
- Explicit is better than implicit
 - Errors should never pass silently
 
- 显式优于隐式
 - 错误永远不应该静默传递
 
What it means, is that you intentionally make your error pass silently. Moreover, you don't event know, which error exactly occurred, because except: passwill catch any exception. 
它的意思是,你故意让你的错误悄悄地过去。此外,您不知道究竟发生了哪个错误,因为except: pass会捕获任何异常。
Second, if we try to abstract away from the Zen of Python, and speak in term of just sanity, you should know, that using except:passleaves you with no knowledge and controlin your system. The rule of thumb is to raise an exception, if error happens, and take appropriate actions. If you don't know in advance, what actions these should be, at least log the error somewhere (and better re-raise the exception):
其次,如果我们试图从 Python 的 Zen 中抽象出来,并以理智的方式说话,你应该知道,使用except:pass会让你对你的系统没有任何知识和控制。经验法则是在发生错误时引发异常并采取适当的措施。如果您事先不知道这些应该是什么操作,至少在某处记录错误(最好重新引发异常):
try:
    something
except:
    logger.exception('Something happened')
But, usually, if you try to catch any exception, you are probably doing something wrong!
但是,通常情况下,如果您尝试捕获任何异常,您可能做错了什么!
回答by Booster
>>> 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 rightnow.
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!
Python 之禅,作者 Tim Peters
美丽总比丑陋好。
显式优于隐式。
简单胜于复杂。
复杂总比复杂好。
扁平比嵌套好。
稀疏比密集好。
可读性很重要。
特殊情况不足以打破规则。
虽然实用性胜过纯度。
错误永远不应该静默传递。
除非明确沉默。
面对模棱两可,拒绝猜测的诱惑。
应该有一种——最好只有一种——明显的方法来做到这一点。
尽管这种方式起初可能并不明显,除非您是荷兰人。
现在总比没有好。
虽然从不总是比正确的现在。
如果实现很难解释,那是个坏主意。
如果实现很容易解释,这可能是一个好主意。
命名空间是一个很棒的想法——让我们做更多的事情!
So, here is my opinion. Whenever you find an error, you should do something to handle it, i.e. write it in logfile or something else. At least, it informs you that there used to be a error.
所以,这是我的意见。每当你发现错误时,你应该做一些事情来处理它,即把它写在日志文件或其他东西中。至少,它会通知您曾经有一个错误。
回答by Aaron Digulla
The main problem here is that it ignores all and any error: Out of memory, CPU is burning, user wants to stop, program wants to exit, Jabberwocky is killing users.
这里的主要问题是它忽略了所有错误:内存不足,CPU 正在燃烧,用户想要停止,程序想要退出,Jabberwocky 正在杀死用户。
This is way too much. In your head, you're thinking "I want to ignore this network error". If something unexpectedgoes wrong, then your code silently continues and breaks in completely unpredictable ways that no one can debug.
这太过分了。在你的脑海中,你在想“我想忽略这个网络错误”。如果出现意外错误,那么您的代码会默默地继续并以完全不可预测的方式中断,而没有人可以调试。
That's why you should limit yourself to ignoring specifically only some errors and let the rest pass.
这就是为什么你应该限制自己只忽略一些错误,让其余的通过。
回答by The Spooniest
The except:passconstruct essentially silences any and all exceptional conditions that come up while the code covered in the try:block is being run.
该except:pass构造基本上消除了在try:块中覆盖的代码正在运行时出现的任何和所有异常情况。
What makes this bad practice is that it usually isn't what you really want.More often, some specific condition is coming up that you want to silence, and except:passis too much of a blunt instrument. It will get the job done, but it will also mask other error conditions that you likely haven't anticipated, but may very well want to deal with in some other way.
这种糟糕做法的原因是它通常不是您真正想要的。更常见的是,出现了一些您想要静音的特定情况,这except: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. SystemExithas 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.
在 Python 中,这一点特别重要的是,根据这种语言的习惯用法,异常不一定是错误。当然,它们经常以这种方式使用,就像在大多数语言中一样。但特别是 Python 偶尔会使用它们来实现一些代码任务的替代退出路径,这实际上不是正常运行情况的一部分,但仍然会不时出现,并且在大多数情况下甚至可能是预期的。SystemExit已经作为一个老例子提到过,但现在最常见的例子可能是StopIteration。以这种方式使用异常引起了很多争议,尤其是当迭代器和生成器第一次被引入 Python 时,但最终这个想法占了上风。
回答by galets
All comments brought up so far are valid. Where possible you need to specify what exactly exception you want to ignore. Where possible you need to analyze what caused exception, and only ignore what you meant to ignore, and not the rest. If exception causes application to "crash spectacularly", then be it, because it's much more important to know the unexpected happened when it happened, than concealing that the problem ever occurred.
到目前为止提出的所有评论都是有效的。在可能的情况下,您需要指定要忽略的确切异常。在可能的情况下,您需要分析导致异常的原因,并且只忽略您打算忽略的内容,而不是其余部分。如果异常导致应用程序“严重崩溃”,那么就这样吧,因为知道意外发生时发生了比隐瞒问题曾经发生过要重要得多。
With all that said, do not take any programming practice as a paramount. This is stupid. There always is the time and place to do ignore-all-exceptions block.
尽管如此,不要将任何编程实践视为最重要的。这是愚蠢的。总是有时间和地点做忽略所有异常块。
Another example of idiotic paramount is usage of gotooperator. When I was in school, our professor taught us gotooperator just to mention that thou shalt not use it, EVER. Don't believe people telling you that xyz should never be used and there cannot be a scenario when it is useful. There always is.
另一个愚蠢至高无上的例子是goto运算符的使用。当我在学校时,我们的教授教我们goto操作员只是提到你永远不要使用它。不要相信人们告诉你永远不应该使用 xyz 并且不可能有它有用的场景。总是有的。
回答by Aaron Hall
Why is “except: pass” a bad programming practice?
Why is this bad?
try: something except: pass
为什么“except: pass”是一种糟糕的编程习惯?
为什么这很糟糕?
try: something except: pass
This catches every possible exception, including GeneratorExit, KeyboardInterrupt, and SystemExit- which are exceptions you probably don't intend to catch. It's the same as catching BaseException.
这会捕获所有可能的异常,包括GeneratorExit,KeyboardInterrupt和SystemExit- 这些是您可能不打算捕获的异常。这和抓一样BaseException。
try:
    something
except BaseException:
    pass
Olderversions of the documentation say:
Since every error in Python raises an exception, using
except:can make many programming errors look like runtime problems, which hinders the debugging process.
由于 Python 中的每个错误都会引发异常,因此使用
except:会使许多编程错误看起来像运行时问题,从而阻碍调试过程。
Python Exception Hierarchy
Python异常层次结构
If you catch a parent exception class, you also catch all of their child classes. It is much more elegant to only catch the exceptions you are prepared to handle.
如果你捕获一个父异常类,你也会捕获它们的所有子类。只捕获您准备处理的异常要优雅得多。
Here's the Python 3 exception hierarchy- do you really want to catch 'em all?:
这是 Python 3异常层次结构- 你真的想抓住它们吗?:
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
           +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning
Don't Do this
不要这样做
If you're using this form of exception handling:
如果您使用这种形式的异常处理:
try:
    something
except: # don't just do a bare except!
    pass
Then you won't be able to interrupt your somethingblock with Ctrl-C. Your program will overlook every possible Exception inside the trycode block. 
然后您将无法something使用 Ctrl-C中断您的块。您的程序将忽略try代码块内的所有可能的异常。
Here's another example that will have the same undesirable behavior:
这是另一个具有相同不良行为的示例:
except BaseException as e: # don't do this either - same as bare!
    logging.info(e)
Instead, try to only catch the specific exception you know you're looking for. For example, if you know you might get a value-error on a conversion:
相反,尝试只捕获您知道要查找的特定异常。例如,如果您知道在转换时可能会出现值错误:
try:
    foo = operation_that_includes_int(foo)
except ValueError as e:
    if fatal_condition(): # You can raise the exception if it's bad,
        logging.info(e)   # but if it's fatal every time,
        raise             # you probably should just not catch it.
    else:                 # Only catch exceptions you are prepared to handle.
        foo = 0           # Here we simply assign foo to 0 and continue. 
Further Explanation with another example
用另一个例子进一步说明
You might be doing it because you've been web-scraping and been getting say, a UnicodeError, but because you've used the broadest Exception catching, your code, which may have other fundamental flaws, will attempt to run to completion, wasting bandwidth, processing time, wear and tear on your equipment, running out of memory, collecting garbage data, etc. 
您这样做可能是因为您一直在进行网络抓取并得到说 a UnicodeError,但是因为您使用了最广泛的异常捕获,您的代码可能具有其他基本缺陷,将尝试运行完成,浪费带宽、处理时间、设备磨损、内存不足、收集垃圾数据等。
If other people are asking you to complete so that they can rely on your code, I understand feeling compelled to just handle everything. But if you're willing to fail noisily as you develop, you will have the opportunity to correct problems that might only pop up intermittently, but that would be long term costly bugs.
如果其他人要求您完成以便他们可以依赖您的代码,我理解感到被迫处理所有事情。但是,如果您愿意在开发过程中大声失败,您将有机会纠正可能只是间歇性出现的问题,但这将是长期代价高昂的错误。
With more precise error handling, you code can be more robust.
通过更精确的错误处理,您的代码可以更健壮。
回答by Sirac
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-Statement 是一个显示代码将在以后插入的语句”,所以如果你想要一个空的 except-statement 可以随意这样做,但是对于一个好的程序,会有成为缺失的一部分。因为你没有处理你应该拥有的东西。出现的异常使您有机会更正输入数据或更改数据结构,这样这些异常就不会再次发生(但在大多数情况下(网络异常、一般输入异常)异常表明程序的下一部分不会很好地执行。例如,一个 NetworkException 可以指示一个断开的网络连接并且程序不能在接下来的程序步骤中发送/接收数据。
But using a pass block for only one execption-block is valid, because you still differenciate beetween the types of exceptions, so if you put all exception-blocks in one, it is not empty:
但是只对一个 execption-block 使用 pass 块是有效的,因为你仍然区分异常的类型,所以如果你把所有的 exception-blocks 放在一个,它不是空的:
try:
    #code here
except Error1:
    #exception handle1
except Error2:
    #exception handle2
#and so on
can be rewritten that way:
可以这样改写:
try:
    #code here
except BaseException as e:
    if isinstance(e, Error1):
        #exception handle1
    elif isinstance(e, Error2):
        #exception handle2
    ...
    else:
        raise
So even multiple except-blocks with pass-statements can result in code, whose structure handles special types of exceptions.
因此,即使有多个带有 pass 语句的except-block 也可能导致代码,其结构处理特殊类型的异常。

