How to print an exception in Python 3?

前端 未结 7 2114
有刺的猬
有刺的猬 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 14:22

    These are the changes since python 2:

        try:
            1 / 0
        except Exception as e: # (as opposed to except Exception, e:)
                               # ^ that will just look for two classes, Exception and e
            # for the repr
            print(repr(e))
            # for just the message, or str(e), since print calls str under the hood
            print(e)
            # the arguments that the exception has been called with. 
            # the first one is usually the message. (OSError is different, though)
            print(e.args)
    

    You can look into the standard library module traceback for fancier stuff.

提交回复
热议问题