Python 异常中的finally

2022-05-18 14:31:51 浏览数 (1)

异常中的finally

  • finally的功能和用法
功能
  • 无论是否发生异常 , 一定会执行的代码块
  • 在函数中, 即便在tryexcept中进行了return也依然会执行finally语法块
  • try语法至少要伴随exceptfinally中的一个
用法
代码语言:javascript复制
try:
    <代码块1>
except:
    <代码块2>
finally:
    <代码块3>

历史
  • python 2.5 之前的版本, finally需要独立使用不可以try配合,之后才演变成现在的模式
代码
代码语言:javascript复制
# coding:utf-8

def test1():
    try:
        1 / 0
    except Exception as e:
        print(e)
    finally:
        return 'finally'


result = test1()
print(result)


def test2():
    try:
        1 / 0
    except Exception as e:
        print('111')
        return e
    finally:
        print('finally')


print('-------')
result = test2()
print(result)


def test3():
    try:
        print('try test 11')
        return 'try'
    except Exception as e:
        print('e')
    finally:
        print('finally test')


print('------')
result = test3()
print(result)


def test4():
    try:
        1 / 0
    except Exception as e:
        print('1')
        return e
    finally:
        print('2')
        return 'finally'


print('----------')
result = test4()
print(result)


def test5():
    try:
        print('1try')
        return 'try'
    except Exception as e:
        print('e')
    finally:
        print('2finally')
        return 'finally'


print('========')
result = test5()
print(result)


def test6():
    try:
        print('try1')
        1 / 0
        print('try3')
    finally:
        # print('i am finally')
        return 'i am finally'


print('-------')
result = test6()
print(result)

0 人点赞