In my application, I’m loading some data from a file. This can fail and raise an exception. As a consequence, I want to log a WARNING and continue to load next data.
I’m doing it like that :
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))
It works but looks heavy. So, my question is: does it exist a way to do it lighter?
It could be something working like that:
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.
I ever saw some answers in other posts suggesting to put it in the loop but, would not it be heavier to manage my parametres?
I’m waiting for any suggestion in this way. Whatever the case my code is working. So, it’s just a question of curiosity on a problem that could also help other programmers…
In this case I might introduce a new function (assuming you can’t or don’t want to change the existing
getDefaultConf):The only difference here is that you’ll get
Noneback for calls that result in an exception. This may or may not be acceptable for your application.