使python 2.6异常向后兼容

m2o*_*m2o 8 python syntax exception python-2.x

我有以下python代码:

 try:
      pr.update()
 except ConfigurationException as e:
      returnString=e.line+' '+e.errormsg
Run Code Online (Sandbox Code Playgroud)

这在python 2.6下工作,但"as e"语法在以前的版本中失败.我怎么解决这个问题?或者换句话说,如何在python 2.6下捕获用户定义的异常(并使用它们的实例变量).谢谢!

Mar*_*ier 12

这是向后兼容和向前兼容的:

import sys
try:
    pr.update()
except (ConfigurationException,):
    e = sys.exc_info()[1]
    returnString = "%s %s" % (e.line, e.errormsg)
Run Code Online (Sandbox Code Playgroud)

这消除了python 2.5及更早版本中的歧义问题,同时仍然没有失去python 2.6/3变体的任何优点,即仍然可以毫不含糊地捕获多个异常类型,例如except (ConfigurationException, AnotherExceptionType):,如果需要进行每类型处理,仍然可以测试对exc_info()[0]==AnotherExceptionType.


Nad*_*mli 9

这是向后兼容的:

try:
    pr.update()
except ConfigurationException, e:
    returnString=e.line+' '+e.errormsg
Run Code Online (Sandbox Code Playgroud)

  • 有关此更改的原因,请参阅PEP 3110:http://www.python.org/dev/peps/pep-3110/ (2认同)

S.L*_*ott 5

请阅读:http://docs.python.org/reference/compound_stmts.html#the-try-statement

这个:http://docs.python.org/whatsnew/2.6.html#pep-3110-exception-handling-changes

不要使用as,使用,.

as语法是特别不向后兼容,因为,语法是不明确的,必须走在Python 3.