美文网首页Python
python try finally和with语句

python try finally和with语句

作者: 青穗黄 | 来源:发表于2018-06-07 11:28 被阅读16次
    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语句

        本文链接:https://www.haomeiwen.com/subject/aobwsftx.html