python - Python 中的 try-else 有什么用?

标签 python try-catch

我正在尝试学习 Python 的次要细节,然后我遇到了 the try-else statement .

try1_stmt ::=  "try" ":" suite
               ("except" [expression [("as" | ",") target]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]

The optional else clause is executed if and when control flows off the end of the try clause. Exceptions in the else clause are not handled by the preceding except clauses.

我想不出在什么情况下这会有用。通常将代码放在 try block 的末尾或放在 else block 中没有实际区别。

else 子句有什么用?它是否用于某些实际代码中?

最佳答案

Usually there's no practical difference between putting code in the end of the try block or in the else block.

What is the else clause good for?

else 子句本身很有趣。它在没有异常但在 finally 子句之前运行。这是它的一个用例,没有合理的替代方案。

如果没有 else 子句,在最终确定之前运行额外代码的唯一选择就是将代码添加到 try 子句的笨拙做法。这很笨拙,因为它有风险 在不打算受 try block 保护的代码中引发异常。

在完成之前运行额外的未 protected 代码的用例并不经常出现。因此,不要期望在已发布的代码中看到很多示例。这有点罕见。

else 子句的另一个用例是它执行在没有异常发生时必须发生的操作以及在处理异常时不会发生的操作。例如:

   recip = float('Inf')
   try:
       recip = 1 / f(x)
   except ZeroDivisionError:
       logging.info('Infinite result')
   else:
       logging.info('Finite result')

最后,在 try block 中 else 子句最常见的用途是进行一些美化(将异常结果和非异常结果对齐在相同的缩进级别)。这种使用始终是可选的,并非绝对必要。

Is it used in some real-world code?

是的,标准库中有很多示例。

关于python - Python 中的 try-else 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130355/

相关文章:

python - Pandas:应用滚动函数来计算新的列值

Python - pip pywin32 失败

python - 使用 BeautifulSoup 在网页上查找特定文本

java - 循环 try-catch 不起作用

flutter - 如何捕捉 "Unable to load asset: assets/images/sample_img_url.png"

python: 无法打开文件 'C:\Program' : [Errno 2] 没有这样的文件或目录

python - 如何将 cv2.frames 发送到浏览器

C# 确定异常是否用消息初始化

c# - 包含 try-catch 的内联方法

java - finally block 的意义