使Python 2.6异常向后兼容

8 投票
4 回答
2110 浏览
提问于 2025-04-15 14:03

我有以下的Python代码:

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

这段代码在Python 2.6下可以正常运行,但在之前的版本中,"as e"这个写法会出错。我该怎么解决这个问题呢?换句话说,我想知道在Python 2.6中,如何捕获用户自定义的异常(并使用它们的实例变量)。谢谢!

4 个回答

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 中必须去掉。

12

这段代码既向后兼容,也向前兼容:

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

它解决了在 Python 2.5 及更早版本中存在的模糊性问题,同时又保留了 Python 2.6 和 3 版本的一些优点。比如,它仍然可以明确地捕获多种异常类型,例如 except (ConfigurationException, AnotherExceptionType):。如果需要对不同类型的异常进行单独处理,还可以通过 exc_info()[0]==AnotherExceptionType 来进行判断。

9

这段代码是向后兼容的:

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

撰写回答