try-except-else-finally

def test(a):
    try:
        print('this is try...')
        if a == 0:
            raise ZeroDivisionError('customize erro')
        # 如果try有return则不再执行else的代码
        return str(10/a)
    # 多个except之间是互斥关系
    except BaseException as e:
        print('this is except 1...' + str(e))
        return 'except 1'
    except ZeroDivisionError as e:
        print('this is except 2...' + str(e))
        return 'except 2'
    #
    else:
        print('this is else...')
        return ('else')
    finally:
        # finally中的代码,无论什么情况都要执行,即使之前有return!
        print('this is finally...即使有return也要先执行finally之后再执行return!')
        # 如果finally中有return会覆盖之前的return,如果finally中没有则用之前的return
        return 'finally'


print('the result is: '+str(test(0)))

1、组合:try-except,try-finally,try-except-else,try-except-finally,try-except-else-finally

2、else的代码是执行成功没有报错的情况才执行,如果try中有return则不会执行else中的代码

3、多个except之间是互斥的关系

4、即使在finally之前有return也会执行finally的代码,finally中的return会覆盖之前的return

猜你喜欢

转载自www.cnblogs.com/turbolxq/p/12132883.html