Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making python 2.6 exception backward compatible

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!

like image 932
m2o Avatar asked Sep 03 '09 12:09

m2o


3 Answers

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.

like image 54
Mario Ruggier Avatar answered Oct 11 '22 02:10

Mario Ruggier


This is backward compatible:

try:
    pr.update()
except ConfigurationException, e:
    returnString=e.line+' '+e.errormsg
like image 37
Nadia Alramli Avatar answered Oct 11 '22 04:10

Nadia Alramli


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.

like image 33
S.Lott Avatar answered Oct 11 '22 03:10

S.Lott