8

我有以下python代码:

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

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

4

4 回答 4

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.

于 2010-03-25T08:12:15.307 回答
9

这是向后兼容的:

try:
    pr.update()
except ConfigurationException, e:
    returnString=e.line+' '+e.errormsg
于 2009-09-03T12:56:38.747 回答
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 中消失。

于 2009-09-03T12:58:44.400 回答
1
try:
    pr.update()
except ConfigurationException, e:
    returnString = e.line + " " + e.errormsg
于 2009-09-03T12:56:58.000 回答