Python: finally 需要一个 try-except 子句吗?
Python: Does finally needs a try-except clause?
假设如下代码。
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 不会在执行流程中返回,而是逐条返回。
当它到达 finally
时,如果在那里抛出错误,它还需要另一个句柄
试一试:
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
所以不,它不会以无限循环结束
示例代码中的 finally 不会捕获来自 some_code_3 的异常。
是否需要捕获来自some_code_3的异常取决于你的设计。
假设如下代码。
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 不会在执行流程中返回,而是逐条返回。
当它到达 finally
时,如果在那里抛出错误,它还需要另一个句柄
试一试:
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
所以不,它不会以无限循环结束
示例代码中的 finally 不会捕获来自 some_code_3 的异常。
是否需要捕获来自some_code_3的异常取决于你的设计。