For example, I am parsing an xml file element, and all 4 elements are required. My code this like this with minidom library:
id = pattern.getElementsByTagName("id")[0].firstChild.data name = pattern.getElementsByTagName("name")[0].firstChild.data trigger = pattern.getElementsByTagName("trigger")[0].firstChild.data test = pattern.getElementsByTagName("test")[0].firstChild.data
If the xml document lack any of the 4 tags, I want to throw an IndexError exception. Should I use 4 try … except blocks to capture each element exception, or I should just capture all the 4 similar exceptions in one big block? The benefit of capturing individual errors is that I can print out more explicit error message regarding the lack of a specific xml element, but it looks verbose. Is there a good practice here?
try: id = pattern.getElementsByTagName("id")[0].firstChild.data except IndexError: raise IndexError('id must exists in the xml file!') try: name = pattern.getElementsByTagName("name")[0].firstChild.data except IndexError: raise IndexError('name must exists in the xml file!') try: test = pattern.getElementsByTagName("test")[0].firstChild.data except IndexError: raise IndexError('test must exists in the xml file!') try: trigger = pattern.getElementsByTagName("trigger")[0].firstChild.data except IndexError: raise IndexError('trigger must exists in the xml file!')
OR
try: id = pattern.getElementsByTagName("id")[0].firstChild.data name = pattern.getElementsByTagName("name")[0].firstChild.data trigger = pattern.getElementsByTagName("trigger")[0].firstChild.data test = pattern.getElementsByTagName("test")[0].firstChild.data except IndexError: raise IndexError('id, name, trigger and test must exist in the xml file!')
Which one is better or both are not great?
Advertisement
Answer
Consider using a loop over the field names and packing the results into a dict instead!
results = {} for field_name in ("id", "name", "trigger", "test"): try: results[field_name] = xml.getElementsByTagName(field_name)[0].firstChild.data except IndexError as ex: raise IndexError(f"failed to read '{field_name}' from xml {repr(ex)}")