假设下面的代码。

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

最佳答案

试试看:

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 - Python:最终是否需要try-except子句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49401575/

10-12 22:01