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

前端 未结 14 1994
感情败类
感情败类 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 18:02

    You can use finally to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)

    myfile = open("test.txt", "w")
    
    try:
        myfile.write("the Answer is: ")
        myfile.write(42)   # raises TypeError, which will be propagated to caller
    finally:
        myfile.close()     # will be executed before TypeError is propagated
    

    In this example you'd be better off using the with statement, but this kind of structure can be used for other kinds of resources.

    A few years later, I wrote a blog post about an abuse of finally that readers may find amusing.

提交回复
热议问题