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 .

print(2/0)

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 .

copyright notice
author[Qing'an slag],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202010121326937.html

Random recommended