如何减少错误处理代码中的 Try 和 Except 语句

How can I reduce Try and Except statements in error-handling code

正在进行更新数据库的项目。新值(行)从包含 Excel 个文件的文件夹中更新。 Excel 文件中的值由员工提供。有时,这些员工在尝试更新数据库时仍在 Excel 文件中工作。这会导致 PermissionError。

为了避免权限错误,我使用了 Try 和 Except 语句。这工作正常,但可能会出现 Excel 文件一段时间未关闭并且白天打开多个 Excel 文件的情况。

因此,只有一个 Try 和 Except 语句是行不通的。因此我使用了三个 Try 和 Except 语句,它们仍然不能保证正确处理错误。

为了解决这个问题,我认为 While 循环或 for 循环中的 break 语句会起作用吗?试图在(第一个)except 块的末尾添加一个 break 语句,但这没有用..

有什么办法可以解决这个问题吗?添加更多 Try 和 Except 语句会起作用,但这看起来很愚蠢。

if update_number_files == 0:
    print("No new files to update")
elif update_number_files >= 1:
    print("Update error")
else:
    print(str(abs(update_number_files)) + " files will be updated")
    for file in selected_update_files:
        try:
            dfs = pd.read_excel(file, "Sheet2")
        except PermissionError:
            print("PermissionError")
            time.sleep(300)
            try:
                dfs = pd.read_excel(file, "Sheet2")
            except PermissionError:
                print("PermissionError")
                time.sleep(300)
                try:
                    dfs = pd.read_excel(file, "Sheet2")
                except PermissionError:
                    print("PermissionError")
                    time.sleep(300)
                    dfs = pd.read_excel(file, "Sheet2")
        New_file.append(dfs)
        join = pd.concat(New_file)

这显然是迭代代码,而不是级联依赖项。是的,使用循环

max_attempt = 3

for file in selected_update_files:
    dfs = None
    for attempt in range(max_attempt):
        try:
            dfs = pd.read_excel(file, "Sheet2")
        except PermissionError:
            print("PermissionError on read attempt", attempt)
            time.sleep(300)

    if not dfs:
        print("Failed to read", file)

这能解决您的问题吗?