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

函数嵌套try except异常的传递

老董-我爱我家房产SEO2020-08-01179围观,108赞

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

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

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

  1、没有异常处理的情况

  1. # -*- coding: utf-8 -*-
  2.  
  3. def testA():
  4. print(name)
  5.  
  6. def testB():
  7. print('在B中')
  8. testA()
  9.  
  10. def testC():
  11. print('在C中')
  12. testB()
  13.  
  14. testC()
  15.  
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中处理异常

  1. # -*- coding: utf-8 -*-
  2.  
  3. def testA():
  4. print(name)
  5.  
  6. def testB():
  7. print('在B中')
  8. testA()
  9.  
  10. def testC():
  11. try:
  12. print('在C中')
  13. testB()
  14. except Exception as e:
  15. print(e)
  16.  
  17. testC()
  18.  
C
B
name 'name' is not defined

很赞哦!

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

文章评论

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

站点信息

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