问题
I have a bit of code that resembles the following:
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()
Is there any mechanism in Python that would allow me to call cleanup just once, only if an exception is raised? Basically the opposite of else.
The best I can think of is:
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()
回答1:
def _cleanup():
# clean it up
return
cleanup = _cleanup
try:
# stuff
except:
# handle it
else:
cleanup = lambda: None
cleanup()
回答2:
The most clear way I can think of is do exactly the opposite of 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()
If the code is enclosed and lets itself be done, you can simplify it by returning or breaking in the else.
回答3:
How about catching all the exceptions with one except clause and dividing up the different parts of your handling with if/elif blocks:
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()
来源:https://stackoverflow.com/questions/24174116/cleanup-after-exception