#!/usr/bin/env python#-*-coding:utf-8-*-#Author:love_cat#exception handling is a common occurrence in Python, where we can not only handle exceptions, but also print exceptions.Try: Print(a)#obviously a is not definedexceptException as E:Print(e)#the output of the program is as follows" "name ' A ' is not defined" "#but that's the only way we don't know where the program was reported wrong.#when we do not use the Try statement, the interpreter will give us a very detailed error, but at this point the program also crashes#How do I get detailed error information when I guarantee that the program does not crash? #at this point, you can use the method under the Traceback moduleImportTracebackTry: Print(a)#A is still not definedexceptException as E:traceback.print_exc ()Print('Ancient Ming Land basin')#The program output results are as follows" "Traceback (most recent): File "f:/satori/python--traceback/exception handling. Py", line $, in <module> print (a) # A is still not defined nameerror:name ' a ' is not defined Gu Ming basin" "#you can see that this and the program crash, the interpreter reported the error is consistent, but our following string is still printed out#in addition to Traceback.print_exc (), you can also use Traceback.format_exc ()#The difference is the Traceback.print_exc () reported the wrong form and the program crashes exactly the same, even the font color is red, I would really think that the program error#but Traceback.format_exc () is returned as a string, but it needs to be added with printTry: Print(a)#A is still not definedexceptException as E:Print(Traceback.format_exc ())#The program output results are as follows" "Traceback (most recent): File "f:/satori/python--traceback/exception handling. Py", line <module> print (a # A is still not defined nameerror:name ' a ' is not defined" "#Although it looks no different from above, the latter is returned as a string with no red-red font. #in addition, TRACEBACK.PRINT_EXC () can also write error messages to the fileTry: Print(a)#A is still not definedexceptException as E:traceback.print_exc (file=open ('Traceback.txt','W', encoding='Utf-8'))#you can see the new Traceback.txt file appears, open the file can see the following information" "Traceback (most recent): File "f:/satori/python--traceback/exception handling. Py", line-in <module> print (a) # A is still not defined nameerror:name ' a ' is not defined" "
Python--traceback Module