Why do we need the “finally” clause in Python?

前端 未结 14 1989
感情败类
感情败类 2020-11-28 16:58

I am not sure why we need finally in try...except...finally statements. In my opinion, this code block

try:
    run_code1()
except          


        
14条回答
  •  日久生厌
    2020-11-28 17:48

    To add to the other answers above, the finally clause executes no matter what whereas the else clause executes only if an exception was not raised.

    For example, writing to a file with no exceptions will output the following:

    file = open('test.txt', 'w')
    
    try:
        file.write("Testing.")
        print("Writing to file.")
    except IOError:
        print("Could not write to file.")
    else:
        print("Write successful.")
    finally:
        file.close()
        print("File closed.")
    

    OUTPUT:

    Writing to file.
    Write successful.
    File closed.
    

    If there is an exception, the code will output the following, (note that a deliberate error is caused by keeping the file read-only.

    file = open('test.txt', 'r')
    
    try:
        file.write("Testing.")
        print("Writing to file.")
    except IOError:
        print("Could not write to file.")
    else:
        print("Write successful.")
    finally:
        file.close()
        print("File closed.")
    

    OUTPUT:

    Could not write to file.
    File closed.
    

    We can see that the finally clause executes regardless of an exception. Hope this helps.

提交回复
热议问题