【问题标题】:how to covert an exception to a string in python [duplicate]如何在python中将异常转换为字符串[重复]
【发布时间】:2020-10-27 00:11:18
【问题描述】:

我正在记录我的代码中的任何错误,我尝试过使用:

try:
    #some deliberately dodgy code
Except Exception:
    print(Exception) #i am actually passing this to a function to add it in a file

但我得到的只是:

【问题讨论】:

  • except Exception as e: ; print(e)
  • 异常是一个类。在 except 子句中,您应该有 Exception as e 才能打印它。

标签: python python-3.x


【解决方案1】:
try:
    #some deliberately dodgy code possibly involving pig's head (ask dodgy Dave)
except Exception as exc:
    print(exc)

exc 不是字符串(它是一个异常对象),但print 将调用其__str__ 方法,该方法将返回用于实例化它的消息字符串

(你不需要叫它exc,你可以叫它任何你喜欢的名字,但是exce是相当常用的)

如果你想要变量中的消息,你总是可以明确地做

message = str(exc)  # now it really is a string

except 块内

【讨论】:

    【解决方案2】:

    Exception是一个类,你应该让一个对象继承自Exception,像这样:

    try:
        #some deliberately dodgy code
    Except Exception e:
        print(e)
    

    【讨论】:

      【解决方案3】:

      您实际上是在正确的轨道上,但您的代码应该如下所示。

      try:
          #some deliberately dodgy code
      except Exception as message:
          print(message)
      

      你可以看看这个帖子,Converting Exception to a string in Python 3,了解更多细节和更深入的了解。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-27
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 2018-06-11
        • 2018-08-31
        • 2019-12-30
        • 2021-08-16
        相关资源
        最近更新 更多