我正在尝试理解 Python 的 try-except 结构。它看起来很复杂,因为它有可选的 finally 和 else 子句。此外,那里可能涉及return、break、continue。您可以决定命名或不命名您捕获的异常等等......
无论如何,我想我现在已经很好地理解了控制流程,但这里引用 Python 文档中的一段话,我觉得这句话有误。
The following points discuss more complex cases when an exception occurs:
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. In all cases, the exception is re-raised after the finally clause has been executed.
引用自https://docs.python.org/3/tutorial/errors.html
第 8.6 点
最后一句话好像不太对。他们这是什么意思?似乎完全错误。我的测试表明,如果您捕获并处理它(当然),则不会重新引发异常。那么...文档中的注释是什么意思?
谁能解释一下?
编辑: 在我问了这个问题后,似乎有人修复了文档页面。是这样吗?
请您参考如下方法:
我刚刚查了一下,因为我也觉得这很奇怪。我认为那里的措辞非常糟糕。您是完全正确的,如果在 except block 内处理异常,则不会重新引发异常。
他们指的是未捕获此类异常的情况:
As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.
这是来自 the same example you posted , 下面几行。
所以,总结一下。文档可能应该说:
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. In all cases, an exception is re-raised after the finally clause has been executed, if it has not been caught in one of the except blocks.
正如在讨论中指出的那样,这似乎是预期的措辞:
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. In all other cases, an exception is re-raised after the finally clause has been executed.
