“This is the 20th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Here is qing ‘an, this chapter is we often encounter a problem, error, abnormal. How should we deal with it, so that it does not affect the subsequent program to run. abnormal

Let’s start with a simple example. Simple couldn’t be simpler.

print(2/0)

The result can be imagined, of course, is an error! The program has been terminated!

So it’s going to prompt the user to point out this exception object, is there any way to prevent it from reporting this error? Of course there is!

Try-except can help us. Try: print(2/0) except ZeroDivisionError: print('Copy the code

Usage: except for the main program, except for the main program to write printing prompts or other programs can be used

ZeroDivisionError = ZeroDivisionError = ZeroDivisionError = ZeroDivisionError = ZeroDivisionError

Let’s see what happens when we handle python exceptions:

In fact, it’s a little bit like if-else, but it’s run by the main program, then judge, then avoid, and then continue to run the code. Take a look at the following example. 3.1. Use exceptions correctly to avoid crashes

While True: first_name = input(" please input name: ") if first_name == 'zhangsan': If last_name == 'lisi': break full_name = int(first_name + last_name) print(full_name)Copy the code

This program, it seems that there is no problem, when we input English characters, will report an error, because the small north added an int character conversion into oh. Adding non-integer types will result in an error!!

ValueError is reported, so let’s avoid it:

While True: first_name = input(" please input name: ") if first_name == 'zhangsan': Break last_name = input(" last_name = input ") if last_name == 'lisi': break try: full_name = int(first_name + last_name) except: Print (" Int can't add like this!" ) else: print(full_name)Copy the code

Here we can prevent it from terminating the program because of an error, never continuing to run the code, and look at the effect:

Now that the exception notification has been successfully avoided, we can continue with the while loop. 3.2. Handle FileNotFoundError errors

This is an exception that cannot find the file. Let’s look at an example:

with open('name_t.txt','r') as nt:
    come = nt.read()
Copy the code

We read an uncreated text and Python tells us:

Name_t. TXT file not found, processing is similar to the previous.

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()) printCopy the code

I’m just trying to tell you. We compare two texts, use try-except to make a judgment, open the first file name_r.txt and read, and then use except to open another file and read and output the content. Split is to split the contents of the text into multiple parts with Spaces as delimiters, presenting the form of a list to us.

Name_t. TXT = name_t. TXT = name_t. TXT = name_t. TXT = name_t. TXT = name_t. TXT = name_t. TXT = name_t. TXT = name_t. TXT Proceed to the next step and open another file.

Have a curious baby ask again, here you have to with with the final print, at the same level is not running the first first, then followed by here we try again after the operation has performed the except the next, so just print results before and after the order is different. 3.3. Open multiple files using functions

Def name_txt(file_name): try: with open(file_name,'r') as nt: nt = nt.read() except: print(" not found ") else: print(nt.split()) file_name = ['123.txt','321.txt','dog.txt'] for file_names in file_name: name_txt(file_names)Copy the code

Here we pass multiple text files using a for loop, define a parameter, pass the parameter to with open, and use try-except to avoid the error, so that the loop can loop through the list. We also give a text file that does not exist to verify that the error is avoided.

3.4, let avoid the information is not 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 the code

We just need to get rid of the error avoidance message, change it to pass and ignore the error message.

Note: here to tell you is the most simple method, there are many detailed usage, but as a quick start, this kind of method to do first understand, the follow-up will slowly explain in detail.