Suggest a cleaner way to handle Python exceptions?


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

Updated on: 27-Sep-2019

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements