current position：Home>Daily python, Chapter 20, exception handling
Daily python, Chapter 20, exception handling
2022-02-01 01:21:34 【Qing'an slag】
「 This is my participation 11 The fourth of the yuegengwen challenge 20 God , Check out the activity details ：2021 One last more challenge 」
This is Qing'an , This chapter is about a problem we often encounter , Report errors 、 abnormal . What should we do with , Let it not affect the operation of subsequent programs . abnormal
First, let's look at a simple example . The simple can't be simpler .
The result is conceivable , Of course, it's the wrong report ！ The program was terminated ！
The user will be prompted , Point out the exception object , Is there any way to prevent it from making such mistakes , Of course. ！
try-except Can help us . try: print(2/0) except ZeroDivisionError: print(' You can't calculate like this ') Copy code
usage ：try: Inside is the main program ,except: It can write print prompt statements or other programs
Qing'an here except There are also exceptions ZeroDivisionError, It's OK not to add it here , The effect is similar .
Let's see how we deal with python The effect after the exception ：
Actually , It's kind of like if-else, But here the main program runs first , Then to judgment , Then to avoid , Avoid running code after success . Take a look at the following example . 3.1、 Use exceptions correctly , Avoid collapse
while True: first_name = input(" Please enter a name ：") if first_name == 'zhangsan': break last_name = input(" Please enter a name ：") if last_name == 'lisi': break full_name = int(first_name + last_name) print(full_name) Copy code
This procedure , There seems to be no problem , When we input English characters , It's going to be a mistake , Because Xiaobei added one int Type characters are converted into oh . Non integer addition will report an error ！！！
See, I reported ValueError error , Next, let's avoid it ：
while True: first_name = input(" Please enter a name ：") if first_name == 'zhangsan': break last_name = input(" Please enter a name ：") if last_name == 'lisi': break try: full_name = int(first_name + last_name) except: print(" Integers can't be added like this ！") else: print(full_name) Copy code
Here we can prevent it from terminating the program because of an error , Never run code again , See the effect ：
Here we successfully avoided the abnormal notice , We can carry on while loop . 3.2、 Handle FileNotFoundError error
In fact, I can't find the file here , And the reported exception . Let's look at an example ：
with open('name_t.txt','r') as nt: come = nt.read() Copy code
We read a text that was not created ,python Will tell us ：
Not found name_t.txt file , How to deal with it , Similar to the following .
try: with open('name_t.txt','r') as nt: come = nt.read() except: with open('123.txt','r') as rd: come_1 = rd.read() print(come_1.split()) print(" I can't find this file ") Copy code
Here for better identification . We used two texts to make a comparison , Use try-except Made a judgment , Opened the first file name_r.txt file , And read , We use except Do open another file and read and output the content .split Is to split the text into multiple parts with spaces as separators , Present us in the form of a list .
To reassure ： Here, we should first judge whether there is name_t.txt file , No files python It will report an exception , We use except Output a file not found , Avoid this mistake . Then perform the next operation , Open another file .
Another curious baby asked , Here you have to with With the last print At the same level , Don't you run the first one first and then , Here we're going to try After running, the next step has been executed except 了 , So it's just that the order of printing results is different . 3.3、 Use the function to open multiple files
def name_txt(file_name): try: with open(file_name,'r') as nt: nt = nt.read() except: print(" I can't find this file ") else: print(nt.split()) file_name = ['123.txt','321.txt','dog.txt'] for file_names in file_name: name_txt(file_names) Copy code
Here we pass multiple text files using for The way of circulation , Define a formal parameter , Give formal parameters to with open, And we use try-except Made a way to avoid mistakes , Let the loop loop loop through the entire list , Xiaobei here also gives a text file that does not exist to verify whether this error is normally avoided .
3.4、 Keep messages from being displayed
def name_txt(file_name): try: with open(file_name,'r') as nt: nt = nt.read() except: pass else: print(nt.split()) file_name = ['123.txt','321.txt','dog.txt'] for file_names in file_name: name_txt(file_names) Copy code
We just need to remove the error avoidance information directly , Change to pass Just ignore this error message .
notes ： Here's the easiest way , There are many more detailed uses of this class , But as a quick start , This kind of method is to understand , I'll explain it slowly and in detail later .
author[Qing'an slag],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python avatar animation, come and generate your own animation avatar
- leetcode 1884. Egg Drop With 2 Eggs and N Floors（python）
- leetcode 1910. Remove All Occurrences of a Substring（python）
- Python and binary
- First acquaintance with Python class
- [Python data collection] scrapy book acquisition and coding analysis
- Python crawler from introduction to mastery (IV) extracting information from web pages
- Python crawler from entry to mastery (III) implementation of simple crawler
- The apscheduler module in Python implements scheduled tasks
- 1379. Find the same node in the cloned binary tree (Java / C + + / Python)
guess what you like
Python connects redis, singleton and thread pool, and resolves problems encountered
Python from 0 to 1 (day 11) - Python data application 1
Python bisect module
Python + OpenGL realizes real-time interactive writing on blocks with B-spline curves
Use the properties of Python VTK implicit functions to select and cut data
Learn these 10000 passages and become a humorous person in the IT workplace. Python crawler lessons 8-9
leetcode 986. Interval List Intersections（python）
leetcode 1860. Incremental Memory Leak（python）
How to teach yourself Python? How long will it take?
Python Matplotlib drawing pie chart
- Django paging (II)
- Concurrent. For Python concurrent programming Futures or multiprocessing?
- Programmers over the age of 25 can't know a few Chinese herbal medicines. Python crawler lessons 9-9
- Python crawler from introduction to pit full series of tutorials (detailed tutorial + various practical combat)
- The second bullet of class in Python
- Python object oriented programming 03: class inheritance and its derived terms
- How IOS developers learn Python Programming 13 - function 4
- Python crawler from introduction to mastery (VI) form and crawler login
- Python crawler from entry to mastery (V) challenges of dynamic web pages
- Deeply understand pandas to read excel, TXT, CSV files and other commands
- Daily python, Chapter 18, class
- "I just want to collect some plain photos in Python for machine learning," he said. "I believe you a ghost!"
- Django view
- Python implements filtering emoticons in text
- When winter comes, python chooses a coat with temperament for mom! Otherwise, there's really no way to start!
- Python crawler - get fund change information
- Highlight actor using Python VTK
- Python crawler actual combat: crawling southern weekend news articles
- leetcode 406. Queue Reconstruction by Height（python）
- leetcode 1043. Partition Array for Maximum Sum （python）
- Python * * packaging and unpacking details
- Python realizes weather query function
- Python from 0 to 1 (day 12) - Python data application 2 (STR function)
- Python from 0 to 1 (day 13) - Python data application 3
- Numpy common operations of Python data analysis series Chapter 8
- How to implement mockserver [Python version]
- Van * Python! Write an article and publish the script on multiple platforms
- Python data analysis - file reading
- Python data De duplication and missing value processing
- Python office automation - play with browser
- Python series tutorial 127 -- Reference vs copy
- Control flow in Python: break and continue
- Teach you how to extract tables in PDF with Python
- leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal（python）
- leetcode 1338. Reduce Array Size to The Half（python）
- Object oriented and exception handling in Python
- How to configure load balancing for Django service
- How to embed Python in go
- Python Matplotlib drawing graphics
- Python object-oriented programming 05: concluding summary of classes and objects