gpt4 book ai didi

python - 为什么在函数中返回抑制引发的异常?

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:16 25 4
gpt4 key购买 nike

检查以下关于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() 将输出,不会弹出任何异常

no matter exception occurs or not

但是如果 finally 子句中的 'return a' 代码被注释掉,输出将捕获未处理的 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

为什么返回码对于捕获异常如此重要?

最佳答案

直接来自 python docs :

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. If the finally clause raises another exception or executes a return or break statement, the saved exception is discarded:

这是有道理的,因为打印这个错误发生在 finally 语句的末尾。您显式提前退出该语句,因此不应执行打印。

关于python - 为什么在函数中返回抑制引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22930809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com