我有以下Python代码:

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

这工作的python 2.6,但以前的版本下的“为e”语法失败。我该如何解决呢?或者换句话说,我怎么赶用户定义的异常(用自己的实例变量)的python 2.6。谢谢!

有帮助吗?

解决方案

这是向后兼容的:

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

其他提示

这是两个向后和向前兼容:

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

此得到在python 2.5摆脱模糊问题的和更早版本,同时仍没有失去任何蟒2.6 / 3变化的优点,即仍然可以清楚地赶上多种异常类型例如except (ConfigurationException, AnotherExceptionType):和,如果需要每型装卸,仍可测试exc_info()[0]==AnotherExceptionType

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

和这样的: HTTP://docs.python .ORG / whatsnew / 2.6.html#PEP-3110-异常处理-变化

不要使用as,使用,

as语法是特别不向后兼容,因为,语法是不明确的,并且必须在Python 3消失。

try:
    pr.update()
except ConfigurationException, e:
    returnString = e.line + " " + e.errormsg
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top