Python:最终需要tryexcept子句吗?

2024-09-30 18:33:51 发布

您现在位置:Python中文网/ 问答频道 /正文

假设以下代码。你知道吗

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

Tags: inanifcodeiterrorsomebe
3条回答

示例代码中的finally不会捕获某些代码3的异常。你知道吗

是否需要从某些代码捕获异常取决于您的设计。你知道吗

试一试:

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

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

python不会返回到执行流中,而是逐个语句返回。你知道吗

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

相关问题 更多 >