Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Suggest a cleaner way to handle Python exceptions?

I have the following code where there is repetitive clean up involved.

try:
    #some code here
except ValueError , e :
    cleanup_p()
    cleanup_q()
    handle_ValueError()
except IOError , e :
    cleanup_m()
    cleanup_n()
    handle_IOError()

Is there an elegant way of handling repetitive clean-ups in exception handling?


1 Answer
Manogna

We can use the finally clause to clean up whether an exception is thrown or not:

try:
  #some code here
except:
  handle_exception()
finally:
  do_cleanup()

If the cleanup is to be done in the event of an exception, we can code like this:

should_cleanup = True
try:
  #some code here
  should_cleanup = False
except:
  handle_exception()
finally:
  if should_cleanup():
    do_cleanup()
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.