This article mainly introduces relevant information about Python's exception handling. Friends who need it can refer to it
Python's exception handling capability is very powerful and can accurately feedback error information to users. In Python, exceptions are also objects and can be manipulated. All exceptions are members of the base class Exception. All exceptions inherit from the base class Exception and are defined in the exceptions module. Python automatically places all exception names in the built-in namespace, so programs do not have to import the exceptions module to use exceptions. Python uses exception objects to represent abnormal situations. When an error is encountered, an exception will be thrown. If the exception object is not handled or caught, the program will terminate execution with a so-called traceback (an error message).
Note: Although most errors will result in an exception, an exception does not necessarily represent an error. Sometimes they are just a warning, and sometimes they may be a termination signal, such as exiting a loop, etc.
1. Keywords related to python exceptions
raise: manually throw/raise exceptions: raise [exception[,data]
try/except: Catch exceptions and handle
pass: ignore exceptions
as: define exception instance (except IOError as e)
finally: code that is executed regardless of whether an exception occurs]
else: if the statement in try If no exception is thrown, execute the statement in else
except Exception as error:
2. Exception types in python
1.StandardError class : If a logic error occurs in the program, this exception will be thrown. The StandardError class is the base class for all restrained exceptions and is placed in the default namespace. Therefore, there is no need to import the exception module when using IOEroor, EOFError, ImportError and other classes.
StopIteration class: Determine whether the loop is executed to the end. If the loop reaches the end, the exception is thrown.
GeneratorExit class: It is an exception raised by the Generator function. This exception is raised when close() is called.
Warning class: Represents warnings caused by code in the program.
3. Basic method:
1.try:
Statement 1
except [exception1(,exception2 ...),[data…]]:
Statement 2
else:
Statement 3
The rules of this exception handling syntax are:
· Execute the statement under try. If an exception is thrown, the execution process will jump to the first except statement.
· If the exception defined in the first except matches the exception raised, the statement in the except is executed.
· If the raised exception does not match the first except, the second except will be searched, and there is no limit to the number of excepts allowed to be written.
· If all excepts do not match, the exception will be passed to the next highest-level try code that calls this code.
· If no exception occurs, the else block code is executed.
import traceback try: 1/0 except Exception as err: print(err) try: f = open("file.txt","r") except IOError as e: print(e) try: f = open("file.txt","r") except Exception as e: print(e)
The output of the last two are exactly the same--------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------------------------------------
2.try:
Statement 1
finally:
Statement 2
The execution rules of this statement are:
· Execute the code under try.
· If an exception occurs, when the exception is passed to the next level try, the code in finally is executed.
· If no exception occurs, the code in finally is executed.
The second try syntax is useful when code needs to be executed regardless of whether an exception occurs. For example, when we open a file in python for read and write operations, no matter whether there is an exception during the operation, I will eventually close the file. These two forms conflict with each other. If you use one, you are not allowed to use the other, and the functions are different
So, under normal circumstances, finally performs some cleaning work, such as: closing files Descriptors, release locks, etc.
Note that in finally, if an exception occurs, if there is no corresponding external capture mechanism, the exception will be thrown layer by layer until the top, and then the interpreter will stop. Generally, add a try except exception capture in the outer layer
3. Manually use raise to raise an exception
1.raise [exception[,data]]
2. In Python, to raise an exception, the simplest form is to enter the keyword raise, followed by the name of the exception to be raised. Exception names identify specific classes: Python exceptions are objects of those classes. When a raise statement is executed, Python creates an object of the specified exception class. The raise statement can also specify parameters for initializing the exception object. To do this, add a comma and the specified parameters (or a tuple of parameters) after the name of the exception class.
3. Example:
try: print("开始测试") raise IOError except IOError: print("定义好的错误") except: print("别的错误")