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