我想跟踪字典中的异常并返回相同的异常。然而,当我这样做时,finally block 给了我一个空字典。该逻辑非常适用于标量。有人可以解释这种行为吗。
在标量上下文中:
def test():
temp = 1
try:
raise ValueError("sdfs")
except:
temp = 2
finally:
temp = temp + 3
return temp
test()
5
带字典:
def test():
temp = dict()
try:
raise ValueError("something")
except Exception as error:
print("error is :{}".format(error))
temp['except'] = "something" + error
finally:
return temp
test()
error is : something
{}
最佳答案
您在异常处理程序中引发了另一个异常,该异常被吞噬了,因为有一个 finally
处理程序从函数返回。
您不能只连接一个异常对象和一个字符串,因此会引发一个额外的 TypeError
,并且永远不会达到对字典的赋值。
首先将异常转换为字符串:
>>> def test():
... temp = dict()
... try:
... raise ValueError("something")
... except Exception as error:
... print("error is :{}".format(error))
... temp['except'] = "something" + str(error)
... finally:
... return temp
...
>>> test()
error is :something
{'except': 'somethingsomething'}
来自try
statement documentation :
If
finally
is present, it specifies a ‘cleanup’ handler. Thetry
clause is executed, including anyexcept
andelse
clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. Thefinally
clause is executed. If there is a saved exception it is re-raised at the end of thefinally
clause. If thefinally
clause raises another exception, the saved exception is set as the context of the new exception. If thefinally
clause executes areturn
orbreak
statement, the saved exception is discarded[.]
(大胆强调我的)。
关于python - 为什么 return 最终给出空字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47777776/