【问题标题】:How do i return error in exception in python?我如何在 python 中返回异常错误?
【发布时间】: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 exampleedit 问题。您曾经能够在 Python 2 中将字符串文字作为异常引发,但这已被弃用很长时间,since 2.5,并在 3.0 中删除。
  • 什么确切地你想回来吗?当您尝试运行此代码时,您是否注意到 TypeError?你看过 raise 的文档了吗?如果没有,这里是为了您的方便:docs.python.org/3/reference/simple_stmts.html#raise

标签: python exception return


【解决方案1】:

如果您只想返回带有类名的错误消息,您可能会这样做:

def proc():
    try:
        a=2/0
    except Exception as e:
        print("Except")
        return repr(e) # Repr is a great solution
    else:
        return "Success"

result=proc()
print("result : ",result)

结果:

Except
result :  ZeroDivisionError(division by zero)

【讨论】:

    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2020-06-15
    • 2021-09-08
    相关资源
    最近更新 更多