3

如何在 python 1.5.2 中获取异常的类型?

这样做:

try:
    raise "ABC"
except Exception as e:
    print str(e)

给出一个语法错误:

  except Exception as e:
                    ^

SyntaxError: invalid syntax

编辑: 这不起作用:

try:
    a = 3
    b = not_existent_variable
except Exception, e:
    print "The error is: " + str(e) + "\n"

a = 3
b = not_existent_variable

因为我只得到参数,而不是实际错误(NameError):

The error is: not_existent_variable

Traceback (innermost last):
  File "C:\Users\jruegg\Desktop\test.py", line 8, in ?
    b = not_existent_variable
NameError: not_existent_variable
4

1 回答 1

10

它是

except Exception, e:

在 Python 1 和 2 中。(虽然as也适用于 Python 2.6 和 2.7)。

(你到底为什么要使用 1.5.2!?)

然后获取您使用的错误类型type(e)。要在您使用的 Python 2 中获取类型名称type(e).__name__,我不知道这是否适用于 1.5.2,您必须查看文档。

更新:它没有,但e.__class__.__name__确实如此。

于 2010-12-16T08:35:20.573 回答