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":
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With