Home >Backend Development >Python Tutorial >Understand Python's exception mechanism
Foreword: When I was working before, I used python to complete a command line window that used the serial port to send SCPI and interact with the microcontroller. When implementing the function, I found that python was used to process the data. The result, whether it is the return of the final correct value or the return of an error value, can be directly returned to the main interface. Obviously it is not possible to directly return data with different meanings, so an exception mechanism is used to handle data with wrong values. Because I didn’t know much about anomalies before, I checked some information here and compiled a few notes.
Article Directory
Summary
(Free learning recommendation: python video tutorial)
1. Understanding of exceptions
1. What is abnormality?
Abnormality means "different from normal conditions". What is normal? Normal means that when the interpreter interprets the code, the code we write conforms to the rules defined by the interpreter, which is normal. When the interpreter finds that a certain piece of code conforms to the grammar but may be abnormal , the interpreter will issue an event to interrupt the normal execution of the program. This interrupt signal is an Exception signal. Therefore, the overall explanation is that when the interpreter detects an error in the program, an exception will be generated. If the program does not handle it, the exception will be thrown and the program will terminate . We can write an int ("m") in a blank .py file, and the result after running is as follows.
This string of fonts is a series of error messages thrown by the interpreter, because the parameters passed in int() only support numeric strings and numbers. Obviously 'm' does not belong to numbers. The input string parameter is wrong, so the interpreter reports a "valueError" error.
2. The difference between errors and exceptions
Overview of Python errors: It refers to syntax or logic errors before the code is run. Take regular syntax errors as an example. When the code we write cannot pass the syntax test, a syntax error will appear directly. It must be corrected before the program is executed. Otherwise, the code written will be meaningless, the code will not run, and it will not be able to Captured. For example, if a = 1 print("hello") is entered in the .py file, the output result is as follows:
Traceback (most recent call last): File "E:/Test_code/test.py",line 1 if a = 1 print("hello") ^SyntaxError: invalid syntax
The function print() was found to have an error, which is that there is a colon missing in front of it: , So the parser will reproduce the line of code with the syntax error and use a small "arrow" to point to the first error detected in the line, so we can directly find the corresponding position and modify its syntax. Of course, in addition to grammatical errors, there are also many program crash errors, such as memory overflow, etc. Such errors are often relatively hidden.
Comparing to errors, Python exceptions mainly occur when the program encounters logical or algorithmic problems during the execution of the program. If the interpreter can handle it, then there is no problem. If it cannot handle it, the program will be terminated directly. , the exception will be thrown, such as the int('m') example in the first point, because the parameter is passed incorrectly, causing a program error. There are all kinds of exceptions caused by logic. Fortunately, our interpreter has built-in various types of exceptions, allowing us to know what kind of exceptions occur, so that we can "prescribe the right medicine".
One thing to note here is that the above syntax errors are identifiable errors, so the interpreter will also throw a SyntaxError exception message by default to feed back to the programmer. So in essence, most errors can be output and printed, but because the error code does not run, it cannot be handled, so capturing the error exception information becomes meaningless.
3. Common python exception types
Here are the most common exception types when we write code. If you encounter other types of exceptions, of course, choose white It’s time~
Exception name | Name resolution |
---|---|
BaseException | All exceptions Base class |
SystemExit | Interpreter request to exit |
KeyboardInterrupt | User interrupts execution (usually Enter ^C) |
Exception | General Error Base Class |
StopIteration | Iterator None More values |
GeneratorExit | The generator generates an exception to notify the exit |
StandardError | Base class for all built-in standard exceptions |
Base class for all numerical calculation errors | |
Floating point calculation error | |
Numerical operation exceeds the maximum limit | |
Division (or modulo) zero (all data types) | |
Assertion statement failed | |
Object does not have this attribute | |
No built-in input, EOF flag reached | |
Base class for operating system errors | |
Input/output operation failed | |
Operating system error | |
System call failed | |
Import Module/Object failed | |
Invalid data query base class | |
In sequence No such index(index) | |
There is no such key in the map | |
Memory Overflow error (not fatal to the Python interpreter) | |
Undeclared/initialized object (no attributes) | |
Accessing uninitialized local variables | |
Weak reference attempts to access an object that has been garbage collected | |
General runtime error | |
Not yet implemented method | |
Syntax error | |
Indentation error | |
mixed with spaces | |
General interpreter system error | ##TypeError |
ValueError | |
UnicodeError Unicode | |
UnicodeDecodeError Unicode | |
UnicodeEncodeError Unicode | |
UnicodeTranslateError Unicode | |
Warning | |
DeprecationWarning | |
FutureWarning | |
OverflowWarning | |
PendingDeprecationWarning | |
RuntimeWarning | |
SyntaxWarning | |
UserWarning | |
The above is the detailed content of Understand Python's exception mechanism. For more information, please follow other related articles on the PHP Chinese website!