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
- 1. Default exception handling mechanism
- 2. try....except....processing mechanism
- 3. try...except...finally..... processing mechanism
- 4. assert assertion processing mechanism
- 5. with...as processing mechanism
- 3. python exception customization
- 1.Exception customization
- 2.Exception throwing raise
- 3. Exception catching
- 4. Precautions for using exceptions
- 1. Don’t rely too much on the exception mechanism
- 2. Don’t Introducing too much code into the try block
- 3. Don’t ignore caught exceptions
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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software