jetjr
jetjr

Reputation: 55

Python Except Specific Key Error

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":

Upvotes: 3

Views: 5393

Answers (3)

Zak Jacobson
Zak Jacobson

Reputation: 23

A slight variation on Paweł Kordowski answer:

a = {}
try:
    a['a']
except KeyError as e:
    # 2 other ways to check what the missing key was
    if 'a' in e.args:
        pass
    if 'a' in e:
        pass
    # reraise the exception if not handled
    else:
        raise

Upvotes: 0

MCBama
MCBama

Reputation: 1490

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

Upvotes: 1

Paweł Kordowski
Paweł Kordowski

Reputation: 2768

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

Upvotes: 5

Related Questions