making python 2.6 exception backward compatible
-
21-09-2019 - |
Question
I have the following python code:
try:
pr.update()
except ConfigurationException as e:
returnString=e.line+' '+e.errormsg
This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their instance variables) under python 2.6. Thank you!
Solution
This is backward compatible:
try:
pr.update()
except ConfigurationException, e:
returnString=e.line+' '+e.errormsg
OTHER TIPS
This is both backward AND forward compatible:
import sys
try:
pr.update()
except (ConfigurationException,):
e = sys.exc_info()[1]
returnString = "%s %s" % (e.line, e.errormsg)
This gets rid of the ambiguity problem in python 2.5 and earlier, while still not losing any of the advantages of the python 2.6/3 variation i.e. can still unambiguously catch multiple exception types e.g. except (ConfigurationException, AnotherExceptionType):
and, if per-type handling is needed, can still test for exc_info()[0]==AnotherExceptionType
.
Read this: http://docs.python.org/reference/compound_stmts.html#the-try-statement
and this: http://docs.python.org/whatsnew/2.6.html#pep-3110-exception-handling-changes
Don't use as
, use a ,
.
The as
syntax is specifically NOT backwards compatible because the ,
syntax is ambiguous and must go away in Python 3.
try:
pr.update()
except ConfigurationException, e:
returnString = e.line + " " + e.errormsg