为什么在函数中返回会抑制引发的异常? [英] Why return in function suppress the exception raised?
问题描述
检查以下有关python中异常处理的代码
Check the following code about exception processing in python
class myException(Exception):
def __str__(self):
return 'this is my exception'
class myException2(Exception):
def __str__(self):
return 'this is my exception 2'
def myfunc():
try:
raise myException2
print('after exception')
except myException:
a = 'exception occur'
print(a)
else:
a = 'exception doesn\'t occur'
print(a)
finally:
a = 'no matter exception occurs or not'
print(a)
return a
然后运行myfunc()将不输出任何内容弹出异常
Then runing myfunc() will output without any exception popping up
no matter exception occurs or not
但是,如果注释了finally子句中的 return a代码,则输出将捕获未处理的myException2,
But if the 'return a' code in finally clause in commented, the output will capture the unhandled myException2,
no matter exception occurs or not
---------------------------------------------------------------------------
myException2 Traceback (most recent call last)
<ipython-input-140-29dfc9311b33> in <module>()
----> 1 myfunc()
<ipython-input-139-ba35768198b8> in myfunc()
1 def myfunc():
2 try:
----> 3 raise myException2
4 print('after exception')
5 except myException:
myException2: this is my exception 2
为什么返回代码对捕获异常如此重要?
Why are the return code so important to do with the capturing of exception?
推荐答案
直接来自 Python文档:
如果最后存在,则指定一个清理处理程序。 try
子句将被执行,包括任何except和else子句。如果
异常发生在任何子句中且未处理,则
异常将被临时保存。将执行finally子句。如果
有一个已保存的异常,则在最后
子句的末尾重新引发该异常。 如果finally子句引发另一个异常或执行
return或break语句,则保存的异常将被丢弃:
这很有意义,因为打印此错误发生在finally语句的末尾。您应尽早明确退出该语句,以免执行打印。
This makes sense, because printing this error happens at the end of the finally statement. You explicitly exit the statement early, so that printing shouldn't be executed.
这篇关于为什么在函数中返回会抑制引发的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!