如何在 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
最佳答案
是
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__
有。
关于python - 在 python 1.5.2 中获取异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4458755/