How To Handle Different Exceptions Raised In Different Python Version
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 Pyth
Solution 1:
This isn't pretty, but it should be workable ...
ParseError = xml.parsers.expat.ExpatError if sys.version < (2, 7) else xml.etree.ElementTree.ParseErrortry:
...
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...)
Solution 2:
Based on mgilson's answer:
from xml.etree import ElementTree
try:
# python 2.7+# pylint: disable=no-memberParseError = ElementTree.ParseError
except ImportError:
# python 2.6-# pylint: disable=no-memberfrom 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
Post a Comment for "How To Handle Different Exceptions Raised In Different Python Version"