1

I'm cleaning up some code, and have run into a handful of situations where there are repetitive cleanup actions in a try/except :

try:
    ...
except KeyError , e :
    cleanup_a()
    cleanup_b()
    cleanup_c()
    handle_keyerror()
except ValuesError , e :
    cleanup_a()
    cleanup_b()
    cleanup_c()
    handle_valueerror()

i'd like to make these a bit more standardized for readability and maintenance. the "cleanup" actions seem to be local to the block , so it's not going to be much cleaner to do the following (though it will standardize it a bit):

def _cleanup_unified():
    cleanup_a()
    cleanup_b()
    cleanup_c()
try:
    ...
except KeyError , e :
    _cleanup_unified()
    handle_keyerror()

except ValuesError , e :
    _cleanup_unified()
    handle_valueerror()

can anyone suggest alternate ways of approaching this ?

1
  • I notice that there are very good responses that are actually answering two different questions. Perhaps some clarification could be added as to which you are looking for? Commented Jul 17, 2013 at 22:15

3 Answers 3

1

You can differenciate the Error by catching all of them in the same except, and testing the type like this:

try:
    ...
except (KeyError, ValuesError) as e :
    cleanup_a()
    cleanup_b()
    cleanup_c()
    if type(e) is KeyError:
        handle_keyerror()
    else:
        handle_valueerror()
Sign up to request clarification or add additional context in comments.

1 Comment

thats a good idea. IIRC, it would be better to if isinstance(e,types.KeyError):
1

If the cleanup can always run, you can use the finally clause, which runs whether an exception is thrown or not:

try:
  do_something()
except:
  handle_exception()
finally:
  do_cleanup()

If the cleanup should only be run in the event of an exception, something like this might work:

should_cleanup = True
try:
  do_something()
  should_cleanup = False
except:
  handle_exception()
finally:
  if should_cleanup():
    do_cleanup()

1 Comment

i thought about your second option (with the should_cleanup flag. it looked less readable for the long term.
0

If the except block is always the same, you can write:

try:
    ...
except (KeyError, ValueError) , e :
    cleanup_a()
    cleanup_b()
    cleanup_c()
    handle_keyerror()

1 Comment

the difference is the handle_keyerror and handle_valueerror. The except block is not the same.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.