How to handle different exceptions raised in different Python version

放肆的年华 提交于 2020-01-05 04:03:22

问题


Trying to parse a malformed XML content with xml.etree.ElementTree.parse() raises different 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'm writing code which must run in Python 2.6 and 2.7. afaik there is no way to define code which runs only in a Python version in Python (analogous to what we could do with #ifdef in C/C++). The only way I see to handle both exceptions is to catch a common parent exception of both (eg Exception). However, that is not ideal because other exceptions will be handled in the same catch block. Is there any other way?


回答1:


This isn't 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 might need to modify what you import based on versions (or catch ImportError while importing the various submodules from xml if they don't exist on python2.6 -- I don't have that version installed, so I can't do a robust test at the moment...)




回答2:


Based 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 in runtime depending on Python's version. Infer Python version from ImportError exception being raised or not
  • Add pylint disable directives to not break Pylint validation
  • For some reason, if only xml is imported, ParseError = xml.etree.ElementTree.ParseError and ParseError = xml.parsers.expat.ExpatError fail; intermediate imports of etree and expat modules fix that


来源:https://stackoverflow.com/questions/36752850/how-to-handle-different-exceptions-raised-in-different-python-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!