异常后清理

时间:2014-06-11 23:15:55

标签: python exception

我有一些类似于以下内容的代码:

try:
    fn()
except ErrorA as e:
    ... do something unique ...
    cleanup()
except ErrorB as e:
    ... do something unique ...
    cleanup()
except ErrorC as e:
    ... do something unique ...
    cleanup()

Python中是否有任何机制允许我只调用cleanup一次,只有在引发异常的情况下?基本上与else相反。

我能想到的最好的是:

error = True
try:
    fn()
    error = False
except ErrorA as e:
    ... do something unique ...
except ErrorB as e:
    ... do something unique ...
except ErrorC as e:
    ... do something unique ...

if error:
    cleanup()

3 个答案:

答案 0 :(得分:4)

def _cleanup():
    # clean it up
    return

cleanup = _cleanup

try:
    # stuff
except:
    # handle it
else:
    cleanup = lambda: None

cleanup()

答案 1 :(得分:2)

我能想到的最明确的方法是与else完全相反:

do_cleanup = True
try:
    fn()
except ErrorA as e:
    ... do something unique ...
except ErrorB as e:
    ... do something unique ...
except ErrorC as e:
    ... do something unique ...
else:
   do_cleanup = False

if do_cleanup:
    cleanup()

如果代码被封闭并让自己完成,您可以通过返回或突破else来简化代码。

答案 2 :(得分:1)

如何使用一个except子句捕获所有异常,并将处理的不同部分与if/elif块分开:

try:
    fn()
except (ErrorA, ErrorB, ErrorC) as e:
    if isinstance(e, ErrorA):
        ... do something unique ...
    elif isinstance(e, ErrorB):
        ... do something unique ...
    else: # isinstance(e, ErrorC)
        ... do something unique ...
    cleanup()