Archive

Posts Tagged ‘error handling’

Catch a specific IOError

March 30, 2012 Leave a comment

Problem
If you want to open a non-existing file, you get the following error message: “IOError: [Errno 2] No such file or directory:...“. How to catch this specific IOError? For instance you want to notify the user that the file is missing instead of just saying “an I/O error occurred”.

Solution
Example:

def read_data_file(self):
    try:
        with open(self.data_file) as f:
           return json.load(f)
    except IOError, e:
        if e.errno == errno.ENOENT:
            print "Error: the given file doesn't exist."
            sys.exit(1)

Errno 2 == errno.ENOENT.

This tip is from here.