views:

323

answers:

4

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!

+7  A: 

This is backward compatible:

try:
    pr.update()
except ConfigurationException, e:
    returnString=e.line+' '+e.errormsg
Nadia Alramli
See PEP 3110 for why this changed: http://www.python.org/dev/peps/pep-3110/
Greg
+1  A: 
try:
    pr.update()
except ConfigurationException, e:
    returnString = e.line + " " + e.errormsg
mipadi
+2  A: 

Read this: http://docs.python.org/reference/compound%5Fstmts.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.

S.Lott
A: 

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.

Mario Ruggier