How to get exception message in Python properly

前端 未结 4 1909
青春惊慌失措
青春惊慌失措 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:17

    To improve on the answer provided by @artofwarfare, here is what I consider a neater way to check for the message attribute and print it or print the Exception object as a fallback.

    try:
        pass 
    except Exception as e:
        print getattr(e, 'message', repr(e))
    

    The call to repr is optional, but I find it necessary in some use cases.


    Update #1:

    Following the comment by @MadPhysicist, here's a proof of why the call to repr might be necessary. Try running the following code in your interpreter:

    try:
        raise Exception 
    except Exception as e:
        print(getattr(e, 'message', repr(e)))
        print(getattr(e, 'message', str(e)))
    

    Update #2:

    Here is a demo with specifics for Python 2.7 and 3.5: https://gist.github.com/takwas/3b7a6effffdef783f2abddffda1439f533

提交回复
热议问题