[英]continue to create tables in for loop after exception is raised
我有一份员工名单,我想为他们创建表格。 即使其中一个表创建失败,我也想继续创建表。 我正在使用 try/except 块,但是当表创建失败时,它会完全失败。 我正在尝试下面的代码。 感谢你的帮助!
employees=[1,2,3,4]
for p in employees:
create_table = f"""create table dim_{p}"""
try:
conn.execute(create_table)
print(f"success for {p}")
except Exception as e:
raise Exception(f"Failed to create table for {p} with error : {{e}}")
我认为您可以保存异常 object 以备后用,而无需引发它。
employees=[1,2,3,4]
exceptions = []
for p in employees:
create_table = f"""create table dim_{p}"""
try:
conn.execute(create_table)
print(f"success for {p}")
except Exception as e:
exceptions.append((p, e)) # save info as a tuple
if exceptions: # after your loop over employees is complete
# handle your errors how you like
fail_msg = '\n'.join([f"{exception[0]} ; {exception[1]}" for exception in exceptions])
raise Exception(f"Failed to create table for the following employees:\n{fail_msg}")
当我运行它时(因为 conn 没有通过任何导入定义)我得到:
Exception: Failed to create table for the following employees:
1 ; name 'conn' is not defined
2 ; name 'conn' is not defined
3 ; name 'conn' is not defined
4 ; name 'conn' is not defined
我正在使用 try/except 块,但是当表创建失败时,它会完全失败。
这是因为您使用了raise Exception(f"Failed to create table for {p} with error: {{e}}")
raising en exception 导致程序中断,避免简单地不使用 raise
为了更好地理解,请看下面的示例:
employees=["1","2",[1,2],"4"]
for i in employees :
try :
print(int(i))
except :
print("error on" , i)
这将是 output:
1个
2个
[1, 2] 上的错误
4个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.