Error handling in file generation (Pythonic way: with / decorators?)

X

xavim

Hi everyone,

I am writing a small tool that generates a file from a list of
sources.
The function dictgen(dictfile, *sources) takes a list of sources path
and an open file object and does the processing.

I am having some problems with how to do proper error handling.
One of the requirements is that the destination file should not be
created if there is any error in the processing.

I have come out with the following code::

dictfile = file(dictpath, 'w')
try:
try:
dictgen(dictfile, *sources)
finally:
dictfile.close()
except error, e:
os.remove(dictpath)
sys.exit(str(e))
except:
os.remove(dictpath)

but it appears to me as somewhat ugly. Is there any more Pythonic
way to abstract this kind of error handling? Maybe 'with' or
decorators could be useful here?

Thanks,
Xavi
 
M

Marc 'BlackJack' Rintsch

I am having some problems with how to do proper error handling.
One of the requirements is that the destination file should not be
created if there is any error in the processing.

I have come out with the following code::

dictfile = file(dictpath, 'w')
try:
try:
dictgen(dictfile, *sources)
finally:
dictfile.close()
except error, e:
os.remove(dictpath)
sys.exit(str(e))
except:
os.remove(dictpath)

but it appears to me as somewhat ugly. Is there any more Pythonic
way to abstract this kind of error handling? Maybe 'with' or
decorators could be useful here?

With ``with`` you can get rid of the inner ``try``/``finally``:

dictfile = open(dictpath, 'w')
try:
with dictfile:
dictgen(dictfile, sources)
except error, e:
os.remove(dictpath)
sys.exit(str(e))
except:
os.remove(dictpath)
raise

Ciao,
Marc 'BlackJack' Rintsch
 
L

Lawrence D'Oliveiro

xavim said:
This should read::

try:
(...)
except:
os.remove(dictpath)
raise

Perhaps:

try :
(...)
except :
try :
os.remove(dictpath)
except :
pass
#end try
raise
#end try

(Just in case.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,266
Latest member
DavidaAlla

Latest Threads

Top