python try finally和with语句

def exe_try():
    try:
        print("start")
        raise KeyError
        return 1
    except KeyError as e:
        print("key error")
        return 2
    else:
        print("other status")
        return 3
    finally:
        print("finally")
        return 4

if __name__ == "__main__":
    result = exe_try()
    print(result)

执行结果

start
key error
finally
4

执行return 2, return 4时,将2,4压入堆栈,最后return时在堆栈中取出一个值(4)

with 语句用来简化,try...finally 写法

你可能感兴趣的:(python try finally和with语句)