[python tutorial] try–except exception capture

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right

Article directory

Anomaly Introduction

What is an exception? An exception is “not normal”.
An abnormal event occurred during the execution of our program. This event affected the normal operation of the program. At this time, a program exception occurred. We were modifying bugs (abnormalities) 80% of the time when we were writing the code. Bugs (abnormalities) are very important. What are the exceptions in python? How to find the abnormal code through the program’s error report.

Catch exception try…except

Write the exception to be caught by the format
Exception code, as e represents the basic information of the stored exception

try :    #Write a try and put the code that might go wrong.
   code snippet
except Exception  as e: # Write an except 
     to handle when an exception is obtained     # Write a handling plan for catching exceptions

See the following example:
The type of error caught here is IOError

try:
    print('-----test--1---')
    open('123.txt','r')
    print('-----test--2---')
except IOError as e:
    print( 'caught exception' ,e)

Running result:
Exception caught, without this 123.txt file

Summary:

illustrate:

1. This program catches the error, because the IOError exception is caught
 with except , and the processing method is added . 2. Except to add the error base class IOError try statement if there is an error, execute the print statement under except , then the error message will be output
 . The result can be seen: the captured error is saved to a variable, and the console can print out specific error information.

working code

try:
    print('-----test--1---')
    open('123.txt','r')
    print('-----test--2---')
except IOError as e:
    print( 'caught exception' ,e)

Running result
No error is reported when the statement in try is executed

Summary:
As can be seen from the above, when there is an exception, the content under except will be executed, and when there is no exception, the content under except will not be executed.

except catch exception type

See the following example:

try:
    print(number)
except IOError:
    print( 'An error occurred' )

The running result is as follows:
Think about it:

The above example program has already used except to catch exceptions. Why do I still see an error message?

answer:

The error type captured by except is IOError, and the exception generated by the program at this time is NameError, so except does not take effect

The modified code is:
modify the type of error to be caught, IOError becomes NameError

try:
    print(number)
except NameError as e:
    print( 'An error occurred' ,e)

The running result is as follows:
Summary
The type of error caught by except corresponds to the type of error, then except takes effect, and the responsible except does not take effect.

Ways to catch multiple exceptions

sample code

try:
    print('-----test--1---')
    open( '123.tx' , 'r' ) # If the 123.txt file does not exist, an IOError exception will be generated 
    print( '-----test--2---' )
    print(num) # If the num variable is not defined, a NameError exception will be raised

except (IOError, NameError) as e:
     #If you want to catch multiple exceptions through one except, you can use a tuple 
    print( 'Caught exception information:' ,e)

Running result 1
catches the first IOError exception

Result 2 The
123.txt file exists, and the NameError exception is caught

Note:
When catching multiple exceptions, you can put the name of the exception to be caught after the except, and use the tuple to store only.

In case of ambiguous error type

When you don’t know the error base class, use Exception uniformly.
Here are just some of them.

Here is the above example to demonstrate, when we are not sure about the type of exception, we can use the Exception type

try:
    print(num)
except Exception  as e:
     print ( 'An error occurred' ,e)

The running result
can still capture the same exception information as the above case

When you don’t know what the base class of the error is, write Exception directly after except (can catch all errors)**

try…except…else…

syntax format

try :
         #The code that may throw an exception 
    except Exception [ as reason]: #The
         code used to handle the exception 
    else :
         #If the code in the try clause does not throw an exception, continue to execute the code here

If the code in try throws an exception and is caught by the except statement, the corresponding exception handling code is executed, in which case the code in else will not be executed

If the code in the try does not throw an exception, the code in the else block is executed.

Example 1

try:
    num = 100 
    print num
except Exception  as errorMsg:
     print ( 'An error occurred: %s' %errorMsg)
 else :
     print ( 'No exception was caught, so glad' )

If there is no exception in the run result
try statement, execute else

example 2

try:
    print(num)
except Exception  as errorMsg:
     print ( 'An error occurred: %s' %errorMsg)
 else :
     print ( 'No exception was caught, so glad' )

If an error occurs in the try statement as a result of running
, in this case, the code in the else will not be executed, and the statement in the except will be executed.

Summary
In try…except…else, that is, if the exception is not caught, then execute the things in the else, if there is an exception in the try statement, the else is not executed.

try…except…finally…

In this structure, the code in the finally clause will always be executed, regardless of whether the code in the try throws an exception, or whether the thrown exception is caught by the except statement. The structure syntax is:

try:
   code snippet
except Exception as e:
     Handling when an exception is obtained
finally:
    Code to be executed with or without exception

case

import time
try:
    f = open('123.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    except :
         #If an exception occurs in the process of reading the file, then it will be caught 
        #For example, pressing ctrl+c 
        pass 
    finally :
        f.close()
        print( 'close file' )
 except :
    print( "No such file" )

illustrate:

123. Each line of data in the .txt file is printed, but I purposely use the time .sleep method to pause for 2 seconds before each line is printed .
The reason for this is to make the program run slower. While the program is running, press Ctrl + c to interrupt (cancel) the program.

We can observe that the KeyboardInterrupt exception is triggered and the program exits. But before the program exits, the finally clause is still executed, closing the file.

The above are some usages of catching exceptions.

Leave a Comment

Your email address will not be published. Required fields are marked *