Reputation: 81
I am familiar with try, except. However I'm looking for a more general method that just runs a simple command before the script stops running after any error is raised.
For example if I'm using xlsxwriter:
import xlsxwriter
wb = xlssxwriter.Workbook
ws = wb.add_worksheet()
for i in range (len(list)):
ws.write(i,0,"Hello World!")
#If this script fails, run ws.close()
Upvotes: 2
Views: 96
Reputation: 1721
This is what context managers are for (the with
statement). The Workbook class actually provides what is necessary.
It is as simple as
with xlsxwriter.Workbook('hello_world.xlsx') as workbook:
worksheet = workbook.add_worksheet()
[...]
In case you want to do other things as well, the try ... except ... else ... finally
statement(s) are what you need. See documentation
Upvotes: 3
Reputation: 155536
For the specific case of calling a close
method (where the object doesn't support the context management protocol natively, so you can't use it bare in a with
statement), you can improve a bit on try
/finally
by using contextlib.closing
to wrap it such that it's with
statement compatible, replacing your code:
ws = wb.add_worksheet()
for i in range (len(list)):
ws.write(i,0,"Hello World!")
with (adding import contextlib
to the top of your file):
with contextlib.closing(wb.add_worksheet()) as ws:
for i in range(len(list)):
ws.write(i,0,"Hello World!")
That calls close
unconditionally when the block is exited, whether by exception, return
, or just naturally leaving the block without error or return
ing (which is usually what you want). If for some reason you only want to call it when you have an exception, you can do:
ws = wb.add_worksheet()
try:
for i in range (len(list)):
ws.write(i,0,"Hello World!")
except: # Okay to use bare except because we re-raise after cleanup
ws.close()
raise # Re-raise whatever exception led us here now that cleanup is done
That will only close
when an exception occurs, and will reraise the exception (because continuing silently in this scenario is probably wrong).
Upvotes: 2
Reputation: 651
Well. In general this is solved by:
try:
code that produces error
finally:
cleanup()
Upvotes: 0