8

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!

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

Comments

9

This is backward compatible:

try:
    pr.update()
except ConfigurationException, e:
    returnString=e.line+' '+e.errormsg

1 Comment

The , syntax is certainly backward compatible, but it is not also forward compatible. This is invalid in Python 3 and raises a syntax error. Yup, it's not a runtime error, but a compile time error that can't be caught. See docs.python.org/library/sys.html#sys.exc_info and @Mario-Ruggier's answer below
5

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.

Comments

1
try:
    pr.update()
except ConfigurationException, e:
    returnString = e.line + " " + e.errormsg

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.