try exception关于异常捕获多重使用

try exception finally 函数内部异常

msg = ""
def test():
    try:
        raise Exception("文件解压失败")
    except NameError:
        pass
    try:
        print("test")
    except Exception:
        pass


def main():
    try:
        test()
        print("main")
    except Exception:
        print("not now")

main() 

函数内部未捕获异常异常被外层异常捕获,且函数内部代码不继续执行。

PS F:\workspace\Template> python .\try.py
not now

函数内部异常被捕获则不会再被捕获

def test():
    try:
        raise Exception("文件解压失败")
    except Exception:
        pass
    try:
        print("test")
    except Exception:
        pass


def main():
    try:
        test()
        print("main")
    except Exception:
        print("not now")

main() 

代码异常被捕获且继续执行

PS F:\workspace\Template> python .\try.py
test
main

异常捕获嵌套

异常被捕获则不影响代码继续执行,且外层不捕获异常,但是try内部代码触发异常以后不再继续执行

def test():
    try:
        try:
            print("in1")
            raise Exception("文件解压失败")
        except Exception:
            pass
        print("in2")
    except Exception:
        print("out")
test()
PS F:\workspace\Template> python .\try.py
in1
in2
def test():
    try:
        try:
            print("in1")
            raise NameError("文件解压失败")
            print("try in2")
        except Exception:
            raise NameError()
            pass
        print("in2")
    except Exception:
        print("out")
test()
PS F:\workspace\Template> python .\try.py
in1
out

本质上触发异常就不继续运行 ,所以尽量将try写的细点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值