gpt4 book ai didi

python - “finally”有多深?

转载 作者:行者123 更新时间:2023-12-03 08:12:23 25 4
gpt4 key购买 nike

假设我有python函数:

def someFunction(file):
try:
for i in file:
i+=1
except:
showWarning()
finally:
file.close()

这个函数在另一个函数中这样调用:
def otherFunction(thing):
if thing:
someFunction(thing)

然后我继续写一个for循环,这样
for i in range(num):
try:
otherFunction(input)
except KeyboardInterrupt:
continue

在此特定情况下,如果在此for循环中发生键盘中断,则将调用函数 finallysomeFunction,或者该函数立即终止,并且for循环中的try/except接管。

换句话说,如果我试图捕获键盘中断,是将其放置在文件关闭所在的第一个函数中还是在for循环中进行比较好?

最佳答案

the documentation指出了try/except/finally的工作原理,其中包括:

the finally clause always executes



如果在 try内的 someFunction块内发生异常,则将执行该块的 finally子句。调用堆栈中更高的代码(即函数 someFunction中的代码)无法改变这一点。

如果在 try块内(或在 try块内调用的代码内)没有发生异常,则 finally子句将不会执行。从您的问题中我不清楚,假设的KeyboardInterrupt应该在哪里发生。例如,如果发生这种情况,则在 for i in file的行上,将执行 finally中的 someFunction。如果它出现在说 otherFunction(input)的行上(实际上是在调用 otherFunction之前),那么 finally中的 someFunction将不会执行,因为那时尚未调用 someFunction

关于python - “finally”有多深?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com