[Python practice 0] Exception Handling

Source: Internet
Author: User

In the previous article, we used python for file reading and simple data processing, but we encountered a problem during processing, it means that an error is caused by the absence of a colon in a row. In the end, we add the if statement to the previous code to determine whether the error occurs. The Code is as follows:

data = open('sketch.txt')for each_line in data:    if not each_line.find(":")==-1:                (role,line_spoke) = each_line.split(":",1)        print(role,end='')        print(' said: ',end='')        print(line_spoke,end='')data.close()

Of course, we can not add the if statement to handle this error here. We can use the exception mechanism to avoid this error and modify the above Code as follows:

 

data = open('sketch.txt')for each_line in data:    try:        (role,line_spoke) = each_line.split(":",1)        print(role,end='')        print(' said: ',end='')        print(line_spoke,end='')    except:        pass    data.close()
Note that the above Code is added with try and try t to capture and handle exceptions. Finally, the pass statement is used to ignore this statement and run the code to print the previous data normally, as follows:
>>> ================================ RESTART ================================>>> Man said:  Is this the right room for an argument?Other Man said:  I've told you once.Man said:  No you haven't!Other Man said:  Yes I have.Man said:  When?Other Man said:  Just now.Man said:  No you didn't!Other Man said:  Yes I did!Man said:  You didn't!Other Man said:  I'm telling you, I did!Man said:  You did not!Other Man said:  Oh I'm sorry, is this a five minute argument, or the full half hour?Man said:  Ah! (taking out his wallet and paying) Just the five minutes.Other Man said:  Just the five minutes. Thank you.Other Man said:  Anyway, I did.Man said:  You most certainly did not!Other Man said:  Now let's get one thing quite clear: I most definitely told you!Man said:  Oh no you didn't!Other Man said:  Oh yes I did!Man said:  Oh no you didn't!Other Man said:  Oh yes I did!Man said:  Oh look, this isn't an argument!Other Man said:  Yes it is!Man said:  No it isn't!Man said:  It's just contradiction!Other Man said:  No it isn't!Man said:  It IS!Other Man said:  It is NOT!Man said:  You just contradicted me!Other Man said:  No I didn't!Man said:  You DID!Other Man said:  No no no!Man said:  You did just then!Other Man said:  Nonsense!Man said:  (exasperated) Oh, this is futile!!Other Man said:  No it isn't!Man said:  Yes it is!>>> 
Similarly, the following error may occur because the file cannot be found when it is opened at the beginning:
>>> Traceback (most recent call last):  File "D:\python\file\sketch.py", line 1, in 
 
      data = open('sketch1.txt')FileNotFoundError: [Errno 2] No such file or directory: 'sketch1.txt'>>> 
 
The system prompts that the file cannot be found. Of course, we can add a file to determine whether the file exists before the file is opened. The Code is as follows:
import osif os.path.exists('sketch.txt'):    data = open('sketch.txt')    for each_line in data:                try:                        (role,line_spoke) = each_line.split(":",1)            print(role,end='')            print(' said: ',end='')            print(line_spoke,end='')        except:            pass        data.close()else:    print('The file is not exists')
Here we add the if statement to determine whether the current file exists. if yes, we can read the file; otherwise, the printed file does not exist. Of course, we can also handle the problem through the exception mechanism. The Code is as follows:
try:    data = open('sketch.txt')    for each_line in data:                try:                        (role,line_spoke) = each_line.split(":",1)            print(role,end='')            print(' said: ',end='')            print(line_spoke,end='')        except:            pass        data.close()except:    print('The file is not exists')
Of course, we can also receive specific types of errors. For example, if the file cannot be found, an IOError occurs. We can use IOError to receive this error, as shown below:
try:    data = open('sketch.txt')    for each_line in data:                try:                        (role,line_spoke) = each_line.split(":",1)            print(role,end='')            print(' said: ',end='')            print(line_spoke,end='')        except:            pass        data.close()except IOError:    print('The file is not exists')
Here, we will briefly introduce the basic usage of exceptions. More in-depth usage will be introduced in the next blog.


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.