Search code examples
pythonxml-parsingpython-3.2

Catch an error in case of bad XML


I am using xml.dom.minidom for parsing some XML from a string. I need to handle an error case when the supplied XML is malformed. What error do I catch?

In other words, what should replace BadXml below?

try:
    from xml.dom import minidom
    in_xml = minidom.parseString(some_string)
except BadXml:
    handle_bad_xml(some_string)

Solution

  • Ultimately the only answer is that you must catch Exception. minidom does not implement DOMException, and while it does use some general exceptions from xml.dom, it also freely uses TypeError and other standard python exceptions whose only single common base is Exception itself.