我有一个代码块,在执行导入的方法时,一些记录发生了异常(请参见下文(。我的目标不是停止执行,而是在出现错误时打印(了解数据的错误(一些值并继续。我尝试了各种方法来使用";尝试除了";,但是运气不好!有人能看一下并提出建议吗?非常感谢!
低于的代码
if student_name not in original_df_names_flat:
for org in orgs:
data = calculate(org, data)
result = imported_module.execute(data) # here's the line where exception happens
return result
else:
return data
if student_name not in original_df_names_flat:
for org in orgs:
data = calculate(org, data)
result = None # May fail to get assigned if error in imported_module
try:
result = imported_module.execute(data) # here's the line where exception happens
except Exception as e:
print(f'{e}') # probably better to log the exception
return result
else:
return data
我想异常可能发生在两个地方。所以试试这个。它涵盖了您的例外行和其他可能性。所以你的程序应该继续运行。
其次,我调整了第二个try子句的缩进,以便循环处理组织中的所有数据。为了返回所有结果,我添加了一个列表"结果"。
if student_name not in original_df_names_flat:
results = []
for org in orgs:
try:
data = calculate(org, data)
except Exception as e:
print(str(e))
try:
result = imported_module.execute(data) # here's the line where exception happens
results.append(result)
except Exception as e:
print(str(e))
return results
else:
return data
下面的解决方案解决了这个问题:
if student_name not in original_df_names_flat:
for org in orgs:
data = calculate(org, data)
try:
result = imported_module.execute(data) # here's the line where exception happens
except exception as e:
print ("exception happened", e)
pass
return data
return result
else:
return data
上述解决方案解决了问题