Swift defer and Python try finally

Swift defer and Python try finally

1 defer

Swift defer and Python try finally_第1张图片

“Use defer to write a block of code that is executed after all other code in the function, just before the function returns. The code is executed regardless of whether the function throws an error. You can use defer to write setup and cleanup code next to each other, even though they need to be executed at different times.”

摘录来自: Apple Inc. “The Swift Programming Language (Swift 4.1 beta)”。 iBooks. https://itunes.apple.com/us/book/the-swift-programming-language-swift-4-1-beta/id1002622538?mt=11

2 Python try finally

try…finally…

在程序中,如果一个段代码必须要执行,即无论异常是否产生都要执行,那么此时就需要使用finally。 比如文件关闭,释放锁,把数据库连接返还给连接池等

import time
try:
    f = open('test.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    except:
        #如果在读取文件的过程中,产生了异常,那么就会捕获到
        #比如 按下了 ctrl+c
        pass
    finally:
        f.close()
        print('关闭文件')
except:
    print("没有这个文件")

你可能感兴趣的:(Swift,Python)