gpt4 book ai didi

python - 这个函数正确吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:32 24 4
gpt4 key购买 nike

在某些异常情况下调用该函数是否正确?这个过程正确吗?处理每个异常是否更好?

def close_all():
try:
ftp.close()
except:
pass
try:
tar.close()
except:
pass
try:
savelist.close()
except:
pass
try:
os.remove(tarname)
except:
pass
exit()

提前致谢。

最佳答案

我认为你应该一一处理每个异常。这将缩短您的代码。首先,请注意 ftp.close() 和其他方法将引发的所有异常。然后一一处理。

示例:

>>> a = 5        # a is an integer
>>> b = "Bingo" # b is a string
>>>
>>> def add_five():
try:
c + 5 # c is not defined. NameError exception is raised
except NameError:
b + 5 # b is a string. TypeError exception is raised
except TypeError:
a + 5 # a is int. No exception is raised
except:
# This last except clause is just in case you forgot to handle any exception
pass
>>>

关于python - 这个函数正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27107990/

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