How to print an exception in Python 3?

前端 未结 7 2113
有刺的猬
有刺的猬 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:41

    Try

    try:
        print undefined_var
    except Exception as e:
        print(e)
    

    this will print the representation given by e.__str__():

    "name 'undefined_var' is not defined"

    you can also use:

    print(repr(e))
    

    which will include the Exception class name:

    "NameError("name 'undefined_var' is not defined",)"

提交回复
热议问题