python - 为什么 return 最终给出空字典?

标签 python python-3.x dictionary exception try-catch

我想跟踪字典中的异常并返回相同的异常。然而,当我这样做时,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. 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, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded[.]

(大胆强调我的)。

关于python - 为什么 return 最终给出空字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47777776/

相关文章:

python - 两个字典列表的平均值

Python __index__ 和评估顺序

python - 删除字符串中的特定字符(Python)

python-3.x - 为什么我的 Flask 应用程序在使用 `python app.py` 执行时可以工作,但在使用 `heroku local web` 或 `flask run` 时却不能工作?

dictionary - 如何在GO中更新复杂 map 中的值

在二维网格游戏板上的移动攻击区域内寻找攻击目标空间的算法

python - 在Python中获取文件的文件夹名称

Python - 使用 NLTK 搜索文本

python-3.x - 使用 numpy arange 创建一系列 float

python - 是否可以在 Python 3 中直接导入枚举字段?