I have a list of employees and I want to create tables for them. I want to continue creating tables even if one of the table creations fail. I am using try/except block but when a table creation fails, it fails totally. I am trying below code. Appreciate your help!
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}}")
CodePudding user response:
I am using try/except block but when a table creation fails, it fails totally.
this is because you have use raise Exception(f"Failed to create table for {p} with error : {{e}}")
raising en exception lead to the programme interrupting , to avoid that simply don't use raise
For better understanding look example below :
employees=["1","2",[1,2],"4"]
for i in employees :
try :
print(int(i))
except :
print("error on" , i)
This will output :
1
2
error on [1, 2]
4
CodePudding user response:
I think you can save the exception object for later without raising it.
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 = (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]"])
raise Exception(f"Failed to create table for the following employees:\n{fail_msg}")