How to print an exception in Python 3?

前端 未结 7 2115
有刺的猬
有刺的猬 2021-01-31 13:48

Right now, I catch the exception in the except Exception: clause, and do print(exception). The result provides no information since it always prints

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 14:30

    Although if you want a code that is compatible with both python2 and python3 you can use this:

    import logging
    try:
        1/0
    except Exception as e:
        if hasattr(e, 'message'):
            logging.warning('python2')
            logging.error(e.message)
        else:
            logging.warning('python3')
            logging.error(e)
    

提交回复
热议问题