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!
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
.
This is backward compatible:
try:
pr.update()
except ConfigurationException, e:
returnString=e.line+' '+e.errormsg
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With