在我的應用程序中,我從文件中加載一些數據。這可能會失敗並引發異常。因此,我想記錄警告並繼續加載下一個數據。Python:如何在異常停止後繼續執行try語句
我正在做這樣的:
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.
我見過的其他職位建議把它的循環,但一些答案,豈不是更重來管理我的參數應用?
我以這種方式等待任何建議。無論我的代碼是如何工作的。所以,這只是一個問題的好奇心,也可以幫助其他程序員......
*重*和*輕*甚至是什麼意思? –
@Klaus Byskov Hoffmann:想象一下,如果數據量增長......在我的第一個例子中有很長的重複!對不起,但我不知道如何用英語中更好的單詞來解釋它(可能是單調乏味或令人厭煩) – VGO
好吧,我現在明白了。 –