Once thrown and no systemexit exception is caught, program execution terminates. If an interactive session encounters an Systemexit exception that is not caught, the session terminates.
One, the catch of the exception
There are several ways to catch exceptions:
1: Use try and except statements
The code is as follows |
Copy Code |
Try Block Except [Exception,[data ...]]: Block Try Block Except [Exception,[data ...]]: Block Else Block |
The rules for this exception handling syntax are:
• Executes the statement under try, and if an exception is thrown, the execution skips to the first except statement.
• If the exception defined in the first except matches the thrown exception, the statement in the except is executed.
• If the exception that is thrown does not match the first except, the second except is searched, and the number of except allowed to be written is unlimited.
• If all except do not match, the exception is passed to the next top-level try code that calls this code.
• If no exception occurs, the else block code is executed.
Sample code:
The code is as follows |
Copy Code |
Try f = open ("file.txt", "R") Except IOError, E: Print E |
The detailed reason for the caught IOError error is placed in Object E, and then the except code block of the exception is run, or you can catch all the exceptions by using the following methods:
The code is as follows |
Copy Code |
Try A=b B=c Except Exception,ex: Print Exception, ":", ex |
What you need to be aware of with the EXCEPT clause is that when multiple except clauses intercept an exception, if there is an inheritance relationship between each exception class, the subclass should be written in the front, otherwise the parent class will intercept the subclass exception directly, and the subclass exception that is placed in the following category will not be executed.
2: Use try and finally
The code is as follows |
Copy Code |
Try Block Finally Block |
The execution rules for this statement are:
• Executes the code under try.
• If an exception occurs, the code in finally is executed when the exception is passed to the next try.
• If no exception occurs, execute the code in finally.
The second try syntax is useful for executing code regardless of whether there is an exception, such as when we open a file in Python to read and write, and I end up shutting down the file regardless of whether an exception occurred during the operation.
These two forms conflict with each other, using one that does not permit the use of the other, and different functions.
Second, manual throw throws an exception
In Python, the simplest form to throw an exception is to enter the keyword raise followed by the name of the exception to be thrown. The exception name identifies the specific class: The Python exception is the object of those classes, and when you execute the Raise statement, Python creates an object of the specified exception class, and the raise statement can also specify parameters to initialize the exception object, After the name of the exception class, add a comma and a specified parameter (or a tuple of parameters).
Sample code:
The code is as follows |
Copy Code |
Try Raise Myerror #自己抛出一个异常 Except Myerror: print ' A error ' |
Raise ValueError, ' invalid argument '
The captured content is:
The code is as follows |
Copy Code |
Type = Vauleerror message = Invalid argument |
Third, tracking view exceptions
When an exception occurs, Python can "remember" the exception that is thrown and the current state of the program, and Python maintains the Traceback (tracking) object, which contains information about the function call stack when an exception occurs, and the exception may be raised in a series of nested function calls, when the program calls each function , Python inserts the function name at the beginning of the function call stack, and once the exception is thrown, Python searches for a corresponding exception handler.
If there is no exception handler in the current function, the current function terminates execution, Python searches for the calling function of the current function, and so on, until a matching exception handler is found, or Python arrives at the main program, the process of finding the appropriate exception handler is called "Stack Toss" (Stack unwinding). The interpreter maintains information about the functions in the drop stack on the one hand, and maintains information about functions that have been "tossed" from the stack on the other.
The code is as follows |
Copy Code |
Try Block Except Traceback.print_exc () |
Iv. using the SYS module to backtrack the final exception
The code is as follows |
Copy Code |
Import Sys Try Block Except Info=sys.exc_info () Print info[0], ":", info[1] |
Or in the following form:
The code is as follows |
Copy Code |
Import Sys TP,VAL,TD = Sys.exc_info () The return value of the Sys.exc_info () is a tuple, (type, value/message, Traceback)
|
The type here is the kind of exception, Value/message is the information or parameter of the exception, traceback the object that contains the call stack information, and this method can be seen as covering the traceback.
All of the above is the theoretical knowledge of error handling, next we have to design a own exception handling class, used to record the Exception log, the error log in accordance with the frequency of a file per hour, save to our designated location. The code is as follows:
The code is as follows |
Copy Code |
#coding: Utf-8 #基于python2.6 Import Logging,os,time,traceback class LOG: def __ Init__ (Self,logger): self.filehandlername = ' Self.filehandler = None Self.loggername = Logger Self.logger = Logging.getlogger (logger) & nbsp; Self.logger.setLevel (logging. DEBUG) self.formatter = logging. Formatter ("=========================ntime:% (asctime) s nlogger:% (name) s nlevel:% (levelname) s nfile:% (filename) s nfun:% (FuncName) s nlineno:% (Lineno) d nmessage:% (message) s ") # console ch = logging. Streamhandler () Ch.setlevel (logging. DEBUG) Ch.setformatter (Self.formatter) Self.logger.addHandler (CH) Path = Os.path.abspath (Os.path.dirname (__file__)) + '/log/' +self.loggername+ '/' print ' Log path= ', path
def SETFH (self): fname = Time.strftime ("%y%m%d%h") If Fname!=self.filehandlername: #移除原来的句柄 If Self.filehandler!=none: Self.logger.removeHandler (Self.filehandler) #设置日志文件保存位置 Path = Os.path.abspath (Os.path.dirname (__file__)) + '/log/' +self.loggername+ '/' Print path If Os.path.isdir (path) = = False: Os.makedirs (PATH) FH = logging. Filehandler (path+fname+ '. Log ') Fh.setlevel (logging. DEBUG) Fh.setformatter (Self.formatter) Self.logger.addHandler (FH) Self.filehandlername = fname Self.filehandler = fh #格式化日志内容 def _fmtinfo (self,msg): If Len (msg) ==0: msg = TRACEBACK.FORMAT_EXC () Return msg Else _tmp = [Msg[0]] _tmp.append (Traceback.format_exc ()) Return ' N**********n '. Join (_TMP) #封装方法 def debug (self,*msg): _info = Self._fmtinfo (msg) Try SELF.SETFH () Self.logger.debug (_info) Except print ' MyLog debug: ' + _info def error (SELF,*MSG): _info = Self._fmtinfo (msg) Try SELF.SETFH () Self.logger.error (_info) Except print ' MyLog error: ' + _info def info (self,*msg): _info = Self._fmtinfo (msg) Try SELF.SETFH () Self.logger.error (_info) Except print ' MyLog info: ' + _info Def warning (self,*msg): _info = Self._fmtinfo (msg) Try SELF.SETFH () Self.logger.error (_info) Except print ' MyLog warning: ' + _info If __name__== ' __main__ ': log = log (' fight ') try: Print 1/0 except: Log.error () #使用系统自己的错误描述 try: Print 2/0 except: log.error (' mistaken, denominator cannot be 0 ') #使用自己的错误描述 |