您的位置: 网站首页> python基础> 当前文章

函数嵌套try except异常的传递

老董-我爱我家房产SEO2020-08-01155围观,142赞

  上节课我们介绍了多个try嵌套后异常的传递效果。现在思考下如果异常是在一个函数中产生的,但是这个函数被其他函数嵌套调用了。比如函数A有一个异常,但是函数B中调用了函数A,函数C又调用了函数B,此时此刻异常如何传递呢?

  按照上述假设,异常是在函数A中产生的,那么如果函数A中没有对这个异常进行处理,那么会传递到函数B中,如果函数B也没有处理异常,那么这个异常会继续传递,以此类推。

  如果所有的函数都没有处理,那么程序就挂掉。我们用代码展示下。

  1、没有异常处理的情况

# -*- coding: utf-8 -*-

def testA():
    print(name)

def testB():
    print('在B中')
    testA()

def testC():
    print('在C中')
    testB()

testC()

在C中
Traceback (most recent call last):
在B中
  File "D:/pyscript/py3script/python66/python66.py", line 14, in <module>
    testC()
  File "D:/pyscript/py3script/python66/python66.py", line 12, in testC
    testB()
  File "D:/pyscript/py3script/python66/python66.py", line 8, in testB
    testA()
  File "D:/pyscript/py3script/python66/python66.py", line 4, in testA
    print(name)
NameError: name 'name' is not defined

  2、函数C中处理异常

# -*- coding: utf-8 -*-

def testA():
    print(name)

def testB():
    print('在B中')
    testA()

def testC():
    try:
        print('在C中')
        testB()
    except Exception as e:
        print(e)

testC()

在C中
在B中
name 'name' is not defined


很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    函数嵌套try except异常的传递文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200