繁体   English   中英

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

[英]cleaner way to handle python exceptions?

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

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

如果清理操作始终可以运行,则可以使用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()

您可以通过将所有错误捕获到相同的异常中来区分错误,并测试如下类型:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM