xml - Python Except Specific Key Error


Keywords:python 


Question: 

I'm parsing an XML file using Beautiful Soup. Sometimes I have entries that are missing one or more of the keys I'm parsing. I want to setup exceptions to handle this. My code looks something like this:

for entry in soup.findAll('entry_name'):
    try:
        entry_dict = dict(entry.attrs)
        x = entry_dict["x"]
        y = entry_dict["y"]
        z = entry_dict["z"]

        d[x] = [y, z]
    except KeyError: 
        y = "0"
        d[x] = [y, z]

The problem is I can have "y", "z" or both "y and z" missing depending on the entry. Is there a way to handle specific KeyErrors? Something like this:

except KeyError "y":
except KeyError "z":
except KeyError "y","z":

2 Answers: 

Personally I wouldn't use a try/except here and instead go for the detection approach instead of the handling approach.

if not 'y'  in entry_dict.keys() and not 'z' in entry_dict.keys():
  # handle y and z missing
elif not 'y' in entry_dict.keys():
  # handle missing y
elif not 'z' in entry_dict.keys():
  # handle missing z
 

You can check for exception arguments:

a = {}
try:
    a['a']
except KeyError as e:
    # handle key errors you want
    if e.args[0] == 'a':
        pass
    # reraise the exception if not handled
    else:
        raise