user1564486
user1564486

Reputation:

Python: Necessary to catch open() exceptions?

I'm opening files in multiple functions, and it seems a bit messy/superfluous to keep 'gracefully' handling potential IOErrors:

try:  
    fileHandle = open(file, 'r')  
except:  
    print "Error: failed to open file %s" % (file)  
    sys.exit(2)

In what contexts is it acceptable to just:

fileHandle = open(file, 'r')

and expect the user to eyeball traceback messages in the case of exception?

Upvotes: 1

Views: 122

Answers (3)

James
James

Reputation: 2795

Use the 'with' keyword.

with open(file, 'r') as fileHandle:
    do_whatever()

This code is more-or-less equivalent to

try:
    fileHandle = open(file, 'r')
except IOError:
    pass
else: 
    do_whatever()
finally:
    fileHandle.close()

Basically, it makes sure that you open and close your files correctly, and catches exceptions.

Upvotes: 1

Sylvain Leroux
Sylvain Leroux

Reputation: 52000

This is the principle of exceptions as implemented in Python and other languages. The exception handling in not necessary local to the function that raise the exception.

If some local processing is meaningful, do it. If you can't do anything useful, just let the exception go up in the call stack until a proper exception handler is found.

http://docs.python.org/2/tutorial/errors.html#handling-exceptions


If you catch an exception just in order to log it, you might want to re-raise it:

try:  
    fileHandle = open(file, 'r')  
except IOError:  
    print "Error: failed to open file %s" % (file, )  
    raise

http://docs.python.org/2/tutorial/errors.html#raising-exceptions

Upvotes: 2

tdelaney
tdelaney

Reputation: 77347

Wrap your application in an outer try/except that prints something a little nicer and logs the gory details. I didn't setup a logger here, but you get the drift:

import os
import sys
import logging
import traceback

try:
    my_application(params)
except (OSError, IOError), e:
    message = "%s - %s." % (e.filename, e.sterror)
    sys.stderr.write("Error: %s. See log file for details%s" % (message, os.linesep))
    logger.error('myapp', message)
    for line in traceback.format_exc().split(os.linesep):
        logger.warn('myapp', line)
    sys.exit(2)

Upvotes: 1

Related Questions