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

xavim xavier.martinezhidalgo at gmail.com
Wed Aug 29 04:58:52 EDT 2007


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




More information about the Python-list mailing list