【问题标题】:How to remove additional text while raising an error in python如何在python中引发错误时删除附加文本
【发布时间】:2021-10-19 01:50:59
【问题描述】:

所以我做了一些随机的东西:

def println(text: str) -> str:
    print(text)
    if not type(text) == str:
        raise TypeError("Text not string type")

println("Hello, World!")

现在,当我在println() 函数中放入一个字符串时,它工作得非常好。但是,如果我在 println() 函数中放入一个整数,它会引发一个 TypeError,其来源位置如下所示:

Traceback (most recent call last):
  File "c:\Users\???\Desktop\leahnn files\python projects (do not delete)\Main files\main.py", line 6, in <module>
    println(1)
  File "c:\Users\???\Desktop\leahnn files\python projects (do not delete)\Main files\main.py", line 4, in println
    raise TypeError("Text not string type")
TypeError: Text not string type

它确实引发了 TypeError,但它说明了它来自哪里。我想知道你是否可以删除它来自的位置,然后说:

TypeError: Text not string type

如果我这样做:

def println(text: str) -> str:
    print(text)
    if not type(text) == str:
        print("TypeError: Text not string type")

它将打印出println() 函数内的整数,并在println() 函数内的整数执行完成后打印TypeError。有可能吗?

【问题讨论】:

  • 是的,这是可能的。但是你为什么要掩盖错误的来源呢?这只会让调试变得更加困难。
  • @Chris 让它看起来更整洁。
  • 为什么这很重要?您希望谁会阅读此错误消息?
  • @Chris 我自己。我这样做是为了好玩。
  • 我建议你习惯看起来不“整洁”的错误。完全压缩上下文信息或错误消息是可能的。但是您很快就会发现,这会使处理错误变得更加令人沮丧。它们变得非常难以理解和排除故障。

标签: python exception


【解决方案1】:

你可以用 try-except 子句 在except 中只打印错误消息。 见https://docs.python.org/3/tutorial/errors.html#handling-exceptions

try:
    println(1)
except TypeError as err:
    print(err)

【讨论】:

  • 谢谢。我还不能更正这个答案,因为它说我可以在 7 分钟内更正一个答案。
  • @Rydex 你的意思是接受吗?
  • 你能把这个写成示例脚本吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 2023-04-04
  • 2010-11-15
  • 2020-11-06
  • 1970-01-01
相关资源
最近更新 更多