gpt4 book ai didi

python - 为什么在 except block 中发生异常时,finally block 不返回最新的异常?

转载 作者:行者123 更新时间:2023-12-04 07:56:37 24 4
gpt4 key购买 nike

我写了一段代码,我使用回溯来返回异常堆栈跟踪。但是我忘了导入回溯。
文件名 - trial_main.py

from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn


app = FastAPI()

class RequestJson(BaseModel):
data: str


@app.post("/trial", status_code=200)
async def trial(req:RequestJson):
try:
status = "default"
resp = {
"status": status,
"reason": "default reason"
}

# error point
a = 10/0

status = "complete"
reason = "Finished converting from base64 to image"

resp = {
"status": status,
"reason": reason
}
except Exception as e:
status = "incomplete"
resp = {
"status": status,
"reason": traceback.format_exc(),
}
finally:
return resp


if __name__ == '__main__':
uvicorn.run("trial_main:app", host="0.0.0.0", port=5001, log_level="info")
令我困惑的是,由于找不到回溯模块,为什么代码没有以异常退出。而是返回之前设置的默认响应。
这是我得到的 API 响应 -
{
"status": "default",
"reason": "default reason"
}
这是我运行 uvicorn 服务器的终端上的输出 -
INFO:     Started server process [14744]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:5001 (Press CTRL+C to quit)
INFO: 127.0.0.1:61809 - "POST /trial HTTP/1.1" 200 OK
Api 端点 -
[POST] http://127.0.0.1:5001/trial
输入重新创建情况 -
{"data": "randomString"}

最佳答案

这里没有发生任何神秘事件。
在 try block 中,您成功地为 resp 赋值变量,然后引发异常并执行到除 block 。您正在尝试将新值分配给 resp ,但 ImportError 发生在语句的右侧,所以 resp仍然包含旧值,它将在 finally block 中返回。异常不会进一步传播,因为有 return在 finally block 中,它只是抑制异常。
为了不被 fastapi 样板分心,所有这些都可以用更简单的例子来说明

def always_return():
"""return 1"""
try:
res = 1
raise Exception()
except Exception:
res = 1 / 0
finally:
return res


def never_return():
"""raises ZeroDivisionError"""

try:
res = 1
raise Exception()
except Exception:
res = 1 / 0
finally:
print("finally block exists, but no return here")
return res
>>> print(always_return())
1
>>> print(never_return())
finally block exists, but no return here
ZeroDivisionError: division by zero... traceback

关于python - 为什么在 except block 中发生异常时,finally block 不返回最新的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66673091/

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