Alan Evangelista
Alan Evangelista

Reputation: 3163

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

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?

Upvotes: 1

Views: 5460

Answers (3)

Ricky
Ricky

Reputation: 1

Very simple solution

except (ValueError):

Upvotes: 0

Alan Evangelista
Alan Evangelista

Reputation: 3163

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

Upvotes: 0

mgilson
mgilson

Reputation: 309929

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...)

Upvotes: 3

Related Questions