循环创建员工数据表遇异常时如何继续执行?技术求助
解决创建数据表失败导致程序终止的问题
你的代码核心问题是在except块里用了raise——只要捕获到创建表的异常,就会主动抛出新异常直接终止程序。要实现“单个创建失败不影响其余”的需求,只需要在异常时记录错误,不要抛出异常就行。
修改后的基础版代码
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: # 仅打印错误信息,不终止循环 print(f"Failed to create table for {p} with error: {str(e)}")
进阶版:收集所有失败记录
如果需要后续统一查看或处理失败的情况,可以把失败的员工ID和错误信息收集起来:
employees=[1,2,3,4] failed_records = [] 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: err_msg = f"员工ID {p} 创建表失败: {str(e)}" print(err_msg) failed_records.append((p, str(e))) # 循环结束后输出所有失败记录 if failed_records: print("\n===== 创建失败汇总 =====") for emp_id, err in failed_records: print(f"员工ID {emp_id}: {err}")
内容的提问来源于stack exchange,提问作者Sara
相关产品推荐
相关产品推荐

