【问题标题】:get exception type in python 1.5.2在 python 1.5.2 中获取异常类型
【发布时间】:2010-12-16 08:33:08
【问题描述】:

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

【问题讨论】:

    标签: python exception syntax-error raise


    【解决方案1】:

    这是

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

    【讨论】:

    • 也许他在 Palm Pilot 上使用它,而开发在 1.5.2 时停止......我的支持现在正在推动你越过 10k 的障碍 - 恭喜!
    • 明智地使用你的新能力,年轻的学徒。 :)
    • 类似的东西...我正在开发一个 telit gsm 模块 (codeproject.com/KB/system/CellularDevTelitGSMPython.aspx),而 1.5.2 在硬件中。但是,您的解决方案似乎不起作用...(请参阅我的编辑)
    • @Jan Rüegg:更新了如何获取类型。 str(e) 会将其转换为字符串,并且不包括该异常的类型名称。
    • 啊,对,当然,这是 1.5.2 中的老式类。试试e.__class__.__name__
    猜你喜欢
    • 2014-12-21
    • 2019-03-08
    • 2011-05-17
    • 2011-01-03
    • 2019-09-22
    • 2012-10-27
    • 2021-10-15
    • 2010-10-08
    相关资源
    最近更新 更多