Getting the exception value in Python

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

    Another way hasn't been given yet:

    try:
        1/0
    except Exception, e:
        print e.message
    

    Output:

    integer division or modulo by zero
    

    args[0] might actually not be a message.

    str(e) might return the string with surrounding quotes and possibly with the leading u if unicode:

    'integer division or modulo by zero'
    

    repr(e) gives the full exception representation which is not probably what you want:

    "ZeroDivisionError('integer division or modulo by zero',)"
    

    edit

    My bad !!! It seems that BaseException.message has been deprecated from 2.6, finally, it definitely seems that there is still not a standardized way to display exception messages. So I guess the best is to do deal with e.args and str(e) depending on your needs (and possibly e.message if the lib you are using is relying on that mechanism).

    For instance, with pygraphviz, e.message is the only way to display correctly the exception, using str(e) will surround the message with u''.

    But with MySQLdb, the proper way to retrieve the message is e.args[1]: e.message is empty, and str(e) will display '(ERR_CODE, "ERR_MSG")'

提交回复
热议问题