【问题标题】:Python: Does finally needs a try-except clause?Python:finally 是否需要 try-except 子句?
【发布时间】:2018-08-30 07:00:40
【问题描述】:

假设下面的代码。

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    some_code_3

假设some_code_3 发生异常。我是否需要在 some_code_3 周围添加一个额外的 try-except 子句(见下文),还是会再次调用 some_code_2 的异常,这原则上可能导致无限循环?

这是保护程序吗?

try:
    some_code_1
except: # will it be called twice, if an error occures in finally?
    some_code_2
finally:
    try:
        some_code_3
    except:
        pass

【问题讨论】:

标签: python except finally


【解决方案1】:

试一试:

try:
    print(abc) #Will raise NameError
except: 
    print("In exception")
finally:
    print(xyz) #Will raise NameError

Output: 
In exception
Traceback (most recent call last):
  File "Z:/test/test.py", line 7, in <module>
    print(xyz)
NameError: name 'xyz' is not defined

所以不,它不会以无限循环结束

【讨论】:

    【解决方案2】:

    python 不会返回执行流程,而是逐语句返回。

    当它到达finally时,如果那里抛出错误,它需要另一个句柄

    【讨论】:

      【解决方案3】:

      示例代码中的 finally 不会从 some_code_3 捕获异常。

      是否需要从 some_code_3 捕获异常取决于您的设计。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        • 2021-07-14
        • 2014-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多