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

2024-05-28 23:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在清理一些代码,遇到了一些在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()

为了便于阅读和维护,我想把这些标准化一点。“清理”操作似乎是块的本地操作,因此执行以下操作不会更干净(尽管它会使其标准化一点):

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

except ValuesError , e :
    _cleanup_unified()
    handle_valueerror()

有人能提出其他方法来解决这个问题吗?你知道吗


Tags: 方法代码def情况cleanuphandletrykeyerror
3条回答

如果except块始终相同,则可以写入:

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

如果清理始终可以运行,则可以使用finally子句,无论是否引发异常都可以运行该子句:

try:
  do_something()
except:
  handle_exception()
finally:
  do_cleanup()

如果在发生异常时只运行清理,则类似的操作可能会起作用:

should_cleanup = True
try:
  do_something()
  should_cleanup = False
except:
  handle_exception()
finally:
  if should_cleanup():
    do_cleanup()

您可以通过在同一个except中捕获所有错误并按如下方式测试类型来区分错误:

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

相关问题 更多 >

    热门问题