Skip to content Skip to sidebar Skip to footer

Cleanup After Exception

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 .

Solution 1:

def_cleanup():
    # clean it upreturn

cleanup = _cleanup

try:
    # stuffexcept:
    # handle itelse:
    cleanup = lambda: None

cleanup()

Solution 2:

The most clear way I can think of is do exactly the opposite of else:

do_cleanup = Truetry:
    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 = Falseif do_cleanup:
    cleanup()

If the code is enclosed and lets itself be done, you can simplify it by returning or breaking in the else.

Solution 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) ase:
    ifisinstance(e, ErrorA):
        ... dosomethingunique ...
    elifisinstance(e, ErrorB):
        ... dosomethingunique ...
    else: # isinstance(e, ErrorC)
        ... dosomethingunique ...
    cleanup()

Post a Comment for "Cleanup After Exception"