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
1. Understanding of exceptions
1. What is an exception?
2. The difference between errors and exceptions
3. Common types of python exceptions
2. python’s five major exception handling mechanisms
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
Copy after login
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
##ArithmeticError
Base class for all numerical calculation errors
FloatingPointError
Floating point calculation error
OverflowError
Numerical operation exceeds the maximum limit
ZeropisionError
Division (or modulo) zero (all data types)
AssertionError
Assertion statement failed
##AttributeError
Object does not have this attribute
EOFError
No built-in input, EOF flag reached
EnvironmentError
Base class for operating system errors
IOError
Input/output operation failed
OSError
Operating system error
WindowsError
System call failed
ImportError
Import Module/Object failed
LookupError
Invalid data query base class
IndexError
In sequence No such index(index)
KeyError
There is no such key in the map
MemoryError
Memory Overflow error (not fatal to the Python interpreter)
NameError
Undeclared/initialized object (no attributes)
UnboundLocalError
Accessing uninitialized local variables
ReferenceError
Weak reference attempts to access an object that has been garbage collected
RuntimeError
General runtime error
NotImplementedError
Not yet implemented method
SyntaxError Python
Syntax error
IndentationError
Indentation error
TabError Tab
mixed with spaces
SystemError
General interpreter system error
##TypeError
Invalid operation on type
ValueError
Invalid parameter passed in
UnicodeError Unicode
Related errors
UnicodeDecodeError Unicode
Error during decoding
UnicodeEncodeError Unicode
Error while encoding
UnicodeTranslateError Unicode
Error while converting
Warning
Basic class for warnings
DeprecationWarning
Warning about deprecated features
FutureWarning
About constructing future semantics There will be a changed warning
number = 'hello'try: print(number[500]) #数组越界访问except IndexError as e: print(e)except Exception as e: #万能异常
print(e)except: #默认处理所有异常
print("所有异常都可处理")print("继续运行...")
Copy after login
输出结果如下所示,会输出系统自带的提示错误:string index out of range,相对于解释器因为异常自己抛出来的一堆红色刺眼的字体,这种看起来舒服多了(能够“运筹帷幄”的异常才是好异常嘛哈哈哈)。另外这里用到“万能异常”Exception,基本所有没处理的异常都可以在此执行。最后一个except表示,如果没有指定异常,则默认处理所有的异常。
finally! #异常没被捕获,也执行了finallyTraceback (most recent call last):
File "E:/Test_code/test.py",line 3,in <module>
print("abc")NameError: name 'abc' is not defined
number = 'hello'try: print(abc) #变量未被定义,抛出NameError异常finally: print("finally!")print("继续运行...")
Copy after login
运行结果:
finally! #异常没被捕获,也执行了finallyTraceback (most recent call last):
File "E:/Test_code/test.py",line 3,in <module>
print("abc")NameError: name 'abc' is not defined
Placing a large amount of code in the try block seems "simple" and the code framework is easy to understand. However, because the code in the try block is too large and the business is too complex, will cause the code to appear in the try block. The possibility of anomalies is greatly increased, which makes it more difficult to analyze the causes of anomalies. - And when the block is too large, it is inevitable to follow the try block with a large number of except blocks to provide different processing logic for different exceptions. If the same try block is followed by a large number of except blocks, you need to analyze the logical relationship between them, which increases the programming complexity. Therefore, You can divide the large try block into multiple small blocks, and then capture and handle exceptions respectively.
3. Don’t ignore caught exceptions
Don’t ignore exceptions! Now that the exception has been caught, the except block should do something useful and handle and fix the exception. It is inappropriate to leave the entire except block empty, or to just print simple exception information! The specific processing method is: ①Handle exceptions. Make appropriate repairs to the exception, and then continue running by bypassing the place where the exception occurred; or use other data to perform calculations instead of the expected method return value; or prompt the user to re-operate. In short, the program should try to repair the exception as much as possible. Allow the program to resume operation. ② Re-raise a new exception. Do everything that can be done in the current running environment as much as possible, then translate the exception, package the exception into an exception of the current layer, and re-pass it to the upper-layer caller. ③Handle exceptions at the appropriate layer. If the current layer does not know how to handle the exception, do not use the except statement in the current layer to catch the exception, and let the upper-layer caller be responsible for handling the exception.
Summary
This article starts with the system default exceptions, explains what exceptions are and summarizes the common exception classes in the system, and then writes how to customize exceptions. From the definition of exceptions to throwing to getting the definition and use of custom exceptions, and finally summarizes the precautions when using Python exceptions.
Related free learning recommendations: python tutorial(Video)
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!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.
Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.
VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.
VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.