python exception handling try/except/else/finally statement

  Exceptions refer to exceptions and violations in a program, such as subscript out of bounds in a sequence, opening a non-existing file, null reference exception, etc. By catching exceptions and handling them properly, you can improve the robustness of your program. If there is no code to handle the exception, the Python interpreter will print the relevant exception information and terminate the program.

  Handling exceptions in Python is done through try/except/else/finally statements. Under their grammatical structure:

try:
    Normal execution block
except A:
    Exception A handle
except B:
    Exception B handle
except:
    Other exception handle
else:
    if no exception,get here
finally:
     print("finally") 

  illustrate:

    1. The code in the try clause prevents a statement that might have an exception.

    2. The except clause is the logic for processing when an exception is caught. The statements in except A and except B indicate the logic of targeted processing when the caught exception is A and the exception type is B. except means to remove all other types except exception types A and B.

    3. The else clause is executed when the code in the try clause executes without exception. The else statement is optional.

    4. The finally clause is executed regardless of whether an exception occurs in the try clause. It is often used to close system resources that cannot be released due to exceptions. The finally clause is optional.

    5. Pay attention to the order of the above try/except A/except B/except/else/finally statements, and the order cannot be changed at will.

  Let's take a look at the implementation method through the case of opening the file.

try:
    fp = open('ip.txt', 'r')
    ip_lst = fp.readlines()
except:
    print "%s file,please check." % ('ip.txt')
    sys.exit(1)

  Use the try/except statement to directly operate the open file, instead of implementing the code by judging the existence of the file and the file type. The program handles it by specifying the IOError exception type, and other exceptions report "unkown error". Although the program handles the exception, it does not show that the opened file resource is closed. The modified code is as follows:

try:
    fp = open('ip.txt', 'r')
    ip_lst = fp.readlines()
except:
    print "%s file,please check." % ('ip.txt')
    sys.exit(1)finally:
    fp.close()

  When the code is executed when the ip.txt file does not exist, the program is abnormally interrupted, and a prompt "NameError: name 'fp' is not defined" is displayed. The reason is because of the scope of the variable defined in the try statement. The variable fp is only valid in the try statement and is a local variable. So in order to make the variable fp global. This can be done using nested try/except statements. The modified code is as follows:

try:
    fp = open('ip.txt', 'r')
    try:
        ip_lst = fp.readlines()
    except:
        print "read %s fail" % ('ip.txt')
        sys.exit()
    finally:
        print "call internal finall close file"
        fp.close()
except:
    print "%s file,please check." % ('ip.txt')
    sys.exit(1)

  Note: If you want to use variables defined in other code blocks at the same level in a code block, you can consider nesting or global variable implementation.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325115502&siteId=291194637