I need to have a file deleted if not all the operations that must be done on it were successful (that is, if an exception is raised). It could have been as simple as using except:, deleting the file and then re-raising the exception, but in that case the original exception would be lost if the file cannot be deleted in the except clause for whatever arcane reason.
The best that I have been able to come up with is this:
try:
file_path = "whatever.jpg"
# do stuff with file
except:
exception_raised = True
raise
finally:
try:
if exception_raised:
os.unlink(file_path)
except:
pass
return file_path # everything OK
Does anybody know of a better, more Pythonic approach?
Another option is to simply store the exception if you don’t want to lose it:
Python 3.x version:
The Python 2.x version is slightly more complex since you need to store the complete exception information manually (otherwise you’d lose the traceback):
Edit: Only catch subclasses of
Exceptionin the innertryblock, since you don’t want do catchSystemExitorKeyboardInterrupthere. Also report any excpetion that occurred during unlinking instead of just dropping it.