Suggest a cleaner way to handle Python exceptions?

PythonServer Side ProgrammingProgramming

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()
raja
Published on 06-Dec-2017 16:03:13
Advertisements