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

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()

最佳答案

def _cleanup():
    # clean it up
    return

cleanup = _cleanup

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

cleanup()

关于python - 异常(exception)后清除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24174116/

10-11 22:04