Getting the exception value in Python

后端 未结 7 1043
一个人的身影
一个人的身影 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:38

    Use repr() and The difference between using repr and str

    Using repr:

    >>> try:
    ...     print(x)
    ... except Exception as e:
    ...     print(repr(e))
    ... 
    NameError("name 'x' is not defined")
    

    Using str:

    >>> try:
    ...     print(x)
    ... except Exception as e:
    ...     print(str(e))
    ... 
    name 'x' is not defined
    

提交回复
热议问题