grep
grep

Reputation: 4026

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

Upvotes: 1

Views: 3630

Answers (3)

Blckknght
Blckknght

Reputation: 104752

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

Upvotes: 2

Davidmh
Davidmh

Reputation: 3865

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.

Upvotes: 2

kindall
kindall

Reputation: 184310

def _cleanup():
    # clean it up
    return

cleanup = _cleanup

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

cleanup()

Upvotes: 4

Related Questions