【发布时间】:2022-12-10 03:03:08
【问题描述】:
我想返回我用 python 编写的代码中的错误。我不能这样做。我该怎么做?
def proc():
try:
a=2/0
except Exception as e:
print("Except")
raise f"{e}"
else:
return "Success"
result=proc()
print("result : ",result)
我尝试使用直接加注但没有用?我能怎么做?
【问题讨论】:
-
如果您希望报告错误,请不要捕获它。你会得到
proc()内的ZeroDivisionError。 -
你不是只想返回错误吗?而不是提高它?
-
这回答了你的问题了吗? python exception message capturing
-
你怎么知道没用?查看如何创建 minimal reproducible example 和 edit 问题。您曾经能够在 Python 2 中将字符串文字作为异常引发,但这已被弃用很长时间,since 2.5,并在 3.0 中删除。
-
什么确切地你想回来吗?当您尝试运行此代码时,您是否注意到 TypeError?你看过 raise 的文档了吗?如果没有,这里是为了您的方便:docs.python.org/3/reference/simple_stmts.html#raise