Getting the exception value in Python

后端 未结 7 948
一个人的身影
一个人的身影 2021-01-29 20:15

If I have that code:

try:
    some_method()
except Exception, e:

How can I get this Exception value (string representation I mean)?

7条回答
  •  孤街浪徒
    2021-01-29 20:19

    For python2, It's better to use e.message to get the exception message, this will avoid possible UnicodeDecodeError. But yes e.message will be empty for some kind of exceptions like OSError, in which case we can add a exc_info=True to our logging function to not miss the error.
    For python3, I think it's safe to use str(e).

提交回复
热议问题