当前位置:首页 > python基础教程 > 当前文章
python基础教程
函数嵌套try except异常的传递
2020-08-01
82赞
python中国网
每篇文章努力于解决一个问题!python高级、python面试全套、操作系统经典课等可移步文章底部。
上节课我们介绍了多个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
相关文章
文章评论
函数嵌套try except异常的传递文章写得不错,值得赞赏