Jonathan Vanasco
Jonathan Vanasco

Reputation: 15680

cleaner way to handle python exceptions?

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 ?

Upvotes: 1

Views: 139

Answers (3)

njzk2
njzk2

Reputation: 39386

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

Upvotes: 1

Michael Butscher
Michael Butscher

Reputation: 10959

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

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

Upvotes: 0

mipadi
mipadi

Reputation: 410572

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

Upvotes: 1

Related Questions