Skip to content
Advertisement

How should I capture multiple similar exceptions in such a case?

For example, I am parsing an xml file element, and all 4 elements are required. My code this like this with minidom library:

JavaScript

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?

JavaScript

OR

JavaScript

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!

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement