gpt4 book ai didi

python - 处理 python 异常的更干净的方法?

转载 作者:行者123 更新时间:2023-12-01 05:40:18 26 4
gpt4 key购买 nike

我正在清理一些代码,并且遇到了一些在 try/except 中存在重复清理操作的情况:

try:
...
except KeyError , e :
cleanup_a()
cleanup_b()
cleanup_c()
handle_keyerror()
except ValuesError , e :
cleanup_a()
cleanup_b()
cleanup_c()
handle_valueerror()

我想让它们更加标准化,以提高可读性和维护性。 “清理”操作似乎是 block 本地的,因此执行以下操作不会更干净(尽管它会稍微标准化):

def _cleanup_unified():
cleanup_a()
cleanup_b()
cleanup_c()
try:
...
except KeyError , e :
_cleanup_unified()
handle_keyerror()

except ValuesError , e :
_cleanup_unified()
handle_valueerror()

任何人都可以建议解决此问题的替代方法吗?

最佳答案

您可以通过在同一个异常(exception)中捕获所有错误并测试类型来区分错误,如下所示:

try:
...
except (KeyError, ValuesError) as e :
cleanup_a()
cleanup_b()
cleanup_c()
if type(e) is KeyError:
handle_keyerror()
else:
handle_valueerror()

关于python - 处理 python 异常的更干净的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17710774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com