Python ValueError错误消息

时间:2010-11-04 14:07:43

标签: python exception exception-handling python-3.x

如何在捕获之后实际打印出ValueError的消息?

3 个答案:

答案 0 :(得分:62)

try:
    ...
except ValueError as e:
    print(e)

答案 1 :(得分:0)

Python 3需要在打印之前将异常强制转换为字符串:

try:
    ...
except ValueError as error:
    print(str(error))

答案 2 :(得分:0)

另一种使用 logging

的方法
import logging
try:
    int("dog")
except Exception as e:
    logging.warning(e)
    logging.error(e)

给予

WARNING:root:invalid literal for int() with base 10: 'dog'
ERROR:root:invalid literal for int() with base 10: 'dog'

[Program finished]

只需输入异常即可,

invalid literal for int() with base 10: 'dog'

[Program finished]

取决于你想如何处理输出