gpt4 book ai didi

python : How to continue execution inside a try statement after an exception stop it

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:58 25 4
gpt4 key购买 nike

在我的应用程序中,我正在从文件中加载一些数据。这可能会失败并引发异常。因此,我想记录警告并继续加载下一个数据。

我就是这样做的:

try:
data_A = getDefaultConf(param_1,param_2)
except Exception as e:
log(WARNING, "Failed to get default parametres: "+str(e))
try:
data_B = getDefaultConf(param_1,param_3)
except Exception as e:
log(WARNING, "Failed to get default parametres: "+str(e))
try:
data_C = getDefaultConf(param_4,param_5)
except Exception as e:
log(WARNING, "Failed to get default parametres: "+str(e))
try:
data_D = getDefaultConf(param_4,param_6)
except Exception as e:
log(WARNING, "Failed to get default parametres: "+str(e))
try:
data_E = getDefaultConf(param_4,param_7)
except Exception as e:
log(WARNING, "Failed to get default parametres: "+str(e))

它可以工作,但看起来很重。所以,我的问题是:是否存在一种使它更轻的方法?它可能是这样工作的:

try:
data_A = getDefaultConf(param_1,param_2)
data_B = getDefaultConf(param_1,param_3)
data_C = getDefaultConf(param_4,param_5)
data_D = getDefaultConf(param_4,param_6)
data_E = getDefaultConf(param_4,param_7)
except Exception as e:
log(WARNING, "Failed to get default parametres: "+str(e))
# Here something that could work like a "continue" statement so that if loading of
# data_2 fails it will store the log and continue by trying to load data_3, etc.

我曾在其他帖子中看到一些建议将其放入循环中的答案,但是,管理我的参数会不会更重?

我正在以这种方式等待任何建议。无论如何,我的代码都能正常工作。所以,这只是对一个问题的好奇心问题,这个问题也可以帮助其他程序员......

最佳答案

在这种情况下,我可能会引入一个新函数(假设您不能或不想更改现有的 getDefaultConf):

def getDefault(x, y):
try:
return getDefaultConf(x,y)
except Exception as e:
log(WARNING, "Failed to get default parametres: "+str(e))
return None

data_A = getDefault(param_1,param_2)
data_B = getDefault(param_1,param_3)
data_C = getDefault(param_4,param_5)
data_D = getDefault(param_4,param_6)
data_E = getDefault(param_4,param_7)

此处唯一的区别是对于导致异常的调用,您将返回 None。这可能会或可能不会被您的应用程序接受。

关于 python : How to continue execution inside a try statement after an exception stop it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11029600/

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