使用不同的选项重复尝试和例外

问题描述 投票:0回答:1

在这种情况下,这对我来说工作得很好,但它只是为代码运行增加了 4 秒的额外时间

try:
    val1 = a
except:
    try:
        val1 = b    
    except:
        try:
            val1 = c
        except:
            try:
                val1 = d
            except:
                try:
                    val1 = e
                except:
                    pass

有没有更好的方法来进行多次尝试和排除?

python python-3.x try-catch except
1个回答
0
投票
  1. 将 try-except 与多个 except 子句一起使用:
try:
    val1 = a
except (NameError, ValueError):  # Handle multiple exceptions
    val1 = b
except (KeyError, IndexError):  # Handle other exceptions
    val1 = c
except:  # Catch-all for any other exception
    val1 = None  # Or handle it differently
  1. 使用带条件赋值的循环
for value in [a, b, c, d, e]:
    try:
        val1 = value
        break  # Exit the loop if successful
    except:
        pass  # Continue to the next value

if val1 is None:
    # Handle case where no value was assigned
  1. 使用字典查找
value_map = {
    'a': lambda: a,
    'b': lambda: b,
    'c': lambda: c,
    'd': lambda: d,
    'e': lambda: e,
}

try:
    val1 = value_map[variable_containing_key]()
except KeyError:
    # Handle invalid key
except Exception as e:
    # Handle other exceptions
© www.soinside.com 2019 - 2024. All rights reserved.