获取 python 1.5.2 中的异常类型

发布于 2024-10-07 17:29:24 字数 704 浏览 0 评论 0原文

如何获取 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

How can I get the type of an Exception in python 1.5.2?

doing this:

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

gives an SyntaxError:

  except Exception as e:
                    ^

SyntaxError: invalid syntax

EDIT:
this does not work:

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

a = 3
b = not_existent_variable

as I only get the argument, not the actual error (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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏有森光若流苏 2024-10-14 17:29:24

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__ 做到了。

It's

except Exception, e:

In Python 1 and 2. (Although as also works in Python 2.6 and 2.7).

(Why on earth are you using 1.5.2!?)

To then get the type of the error you use type(e). To get the type name in Python 2 you use type(e).__name__, I have no idea if that works in 1.5.2, you'll have to check the docs.

Update: It didn't, but e.__class__.__name__ did.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文