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

前端 未结 14 1946
感情败类
感情败类 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:46

    Using delphi professionally for some years taught me to safeguard my cleanup routines using finally. Delphi pretty much enforces the use of finally to clean up any resources created before the try block, lest you cause a memory leak. This is also how Java, Python and Ruby works.

    resource = create_resource
    try:
      use resource
    finally:
      resource.cleanup
    

    and resource will be cleaned up regardless of what you do between try and finally. Also, it won't be cleaned up if execution never reaches the try block. (i.e. create_resource itself throws an exception) It makes your code "exception safe".

    As to why you actually need a finally block, not all languages do. In C++ where you have automatically called destructors which enforce cleanup when an exception unrolls the stack. I think this is a step up in the direction of cleaner code compared to try...finally languages.

    {    
      type object1;
      smart_pointer object1(new type());
    } // destructors are automagically called here in LIFO order so no finally required.
    

提交回复
热议问题