How to get exception message in Python properly

前端 未结 4 1908
青春惊慌失措
青春惊慌失措 2020-11-27 13:25

What is the best way to get exceptions\' messages from components of standard library in Python?

I noticed that in some cases you can get it via message

4条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 14:09

    I too had the same problem. Digging into this I found that the Exception class has an args attribute, which captures the arguments that were used to create the exception. If you narrow the exceptions that except will catch to a subset, you should be able to determine how they were constructed, and thus which argument contains the message.

    try:
       # do something that may raise an AuthException
    except AuthException as ex:
       if ex.args[0] == "Authentication Timeout.":
          # handle timeout
       else:
          # generic handling
    

提交回复
热议问题