[英]cleaner way to handle python exceptions?
I'm cleaning up some code, and have run into a handful of situations where there are repetitive cleanup actions in a try/except : 我正在清理一些代码,并且遇到了在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()
i'd like to make these a bit more standardized for readability and maintenance. 我想使这些更加标准化,以提高可读性和维护性。 the "cleanup" actions seem to be local to the block , so it's not going to be much cleaner to do the following (though it will standardize it a bit):
“清除”动作似乎是块的局部内容,因此执行以下操作不会变得更加干净(尽管它将使它标准化):
def _cleanup_unified():
cleanup_a()
cleanup_b()
cleanup_c()
try:
...
except KeyError , e :
_cleanup_unified()
handle_keyerror()
except ValuesError , e :
_cleanup_unified()
handle_valueerror()
can anyone suggest alternate ways of approaching this ? 任何人都可以建议解决此问题的替代方法吗?
If the cleanup can always run, you can use the finally
clause, which runs whether an exception is thrown or not: 如果清理操作始终可以运行,则可以使用
finally
子句,无论是否引发异常,该子句都会运行:
try:
do_something()
except:
handle_exception()
finally:
do_cleanup()
If the cleanup should only be run in the event of an exception, something like this might work: 如果清除仅应在发生异常的情况下运行,则可能会执行以下操作:
should_cleanup = True
try:
do_something()
should_cleanup = False
except:
handle_exception()
finally:
if should_cleanup():
do_cleanup()
You can differenciate the Error by catching all of them in the same except, and testing the type like this: 您可以通过将所有错误捕获到相同的异常中来区分错误,并测试如下类型:
try:
...
except (KeyError, ValuesError) as e :
cleanup_a()
cleanup_b()
cleanup_c()
if type(e) is KeyError:
handle_keyerror()
else:
handle_valueerror()
If the except
block is always the same, you can write: 如果
except
块始终相同,则可以编写:
try:
...
except (KeyError, ValueError) , e :
cleanup_a()
cleanup_b()
cleanup_c()
handle_keyerror()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.