How to handle different exceptions thrown in different Python versions

Trying to parse malformed XML content using xml.etree.ElementTree.parse () throws another exception in Python 2.6.6 and Python 2.7.5

Python 2.6: xml.parsers.expat.ExpatError

Python 2.7: xml.etree.ElementTree.ParseError

I am writing code that needs to run in Python 2.6 and 2.7. afaik there is no way to define code that only works in the Python version in Python (similar to what we could do C # ifdef in C / C ++). The only way I can handle both exceptions is by catching the common parent exception of both (like an exception). However, this is not ideal because other exceptions will be handled in the same catch block. Is there another way?

+1


source to share


2 answers


It's not pretty, but it should be workable ...

ParseError = xml.parsers.expat.ExpatError if sys.version < (2, 7) else xml.etree.ElementTree.ParseError

try:
    ...
except ParseError:
    ...

      



You may need to change what you import based on versions (or catch ImportError

when importing different submodules from xml

if they don't exist on python2.6 - I don't have a version installed so I can't do a reliable test at the moment ... )

+3


source


Building on mgilson's answer:

from xml.etree import ElementTree

try:
    # python 2.7+
    # pylint: disable=no-member
    ParseError = ElementTree.ParseError
except ImportError:
    # python 2.6-
    # pylint: disable=no-member
    from xml.parsers import expat
    ParseError = expat.ExpatError

try:
    doc = ElementTree.parse(<file_path>)
except ParseError:
    <handle error here>

      



  • Define ParseError at runtime depending on Python version. Output Infer Python version from ImportError exception or not
  • Add disable directives to avoid breaking Pylint validation
  • For some reason, if only xml is imported, ParseError = xml.etree.ElementTree.ParseError and ParseError = xml.parsers.expat.ExpatError fails; an intermediate import of the etree and expat modules sets that
0


source







All Articles