【发布时间】: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 我自己。我这样做是为了好玩。
-
我建议你习惯看起来不“整洁”的错误。完全压缩上下文信息或错误消息是可能的。但是您很快就会发现,这会使处理错误变得更加令人沮丧。它们变得非常难以理解和排除故障。