python - 在 python 1.5.2 中获取异常类型

标签 python exception syntax-error raise

如何在 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/

相关文章:

python - POST 查询访问网站上的表数据 (Python)

Python,pandas 根据停止条件找到每一行的长度

python - 基于不同的 DataFrame 在 pandas DataFrame 中追加列

php - 解析错误 : syntax error, 本地主机上的文件意外结束

Python 3 : Unexpected EOF when parsing

Python - 将矩阵转换为边列表/长格式

c# - Entity Framework 代码优先和数据库优先错误/冲突

c++ - CMAKE Compile_Flag

ios - 在WKWebview中突出显示文本时发生JavaScript异常

python - sqlite3.操作错误: near "?": syntax error in python -- using 'IN' operator