[Python] in python, traceback is used to handle exception information.
Recently, a program has been compiled. This program can get the folder and file list updated by the specified folder within the set time, and perform some operations based on the updated list. Because the programs written are run on the server, in order to ensure that the program is running, exceptions are not thrown out from time to scare other users, and exception handling is added to the program. Sort out the online materials and try to use sys. exce_info () and traceback together. The results are still good. The following information shows how to handle exceptions. type is the exception type, and value is the cause of the exception, traceback is the exception information obtained through traceback, which can locate the code that causes the exception.
22:07:56 ----------------------------------- type: <type 'exceptions. typeerror'> value: string indices must be integers, not strtraceback: [('filename ', row number, 'function name', 'Abnormal code line')]
Use the following two rows to record exceptions in try... try t. Specific requirements are required for how the program continues after an exception occurs.
tp,val,td = sys.exc_info()Log.logerexception(tp,val,td)
The Code is as follows:
1 import OS 2 import time 3 import traceback 4 import sys 5 6 def logerexception (tp, val, td): 7 etype = str (tp) 8 evalue = str (val) 9 etb = traceback. extract_tb (td) 10 errormsg = "type:" + etype + "\ n" 11 errormsg + = "value:" + evalue + "\ n" 12 errormsg + = "traceback: "+ str (etb) +" \ n "13 writetofile (errormsg) 14 15 def writetofile (errormsg): 16 logfilepath = OS. path. abspath ('. ') + "/log" 17 if not OS. path. exists (logfilepath): 18 OS. mkdir (logfilepath) 19 20 logfile = time. strftime ("% Y % m % d", time. localtime () + ". txt "21 fp = open (logfilepath +"/"+ logfile," a ") 22 ISOTIMEFORMAT =" % Y-% m-% d % X "23 happeningtime = time. strftime (ISOTIMEFORMAT, time. localtime () 24 usermsg = "" 25 usermsg + = happeningtime + "\ n --------------------------------- \ n" 26 usermsg + = errormsg27 fp. write (usermsg + "\ n") 28 fp. close ()View Code