【发布时间】:2021-12-06 10:41:11
【问题描述】:
def println(text: str):
try:
print(text)
if not type(text) == str:
raise TypeError(f"argument \"text\" should be type \"str\". not type \"{type(text)}\"".)
except TypeError as err:
print(err)
这很好用,它说:
argument "text" should be type "str". not type "<class 'int'>".
但我看不出它来自哪条线路。它来自第 4 行,并没有说明错误来自哪一行。这使得调试错误变得困难且令人沮丧。
【问题讨论】:
-
如果您没有发现错误,解释器会很高兴地向您显示完整的回溯(包括行号)。抛出错误只是为了在同一范围内捕获它似乎不是最好的实现。
print(text)也能很好地处理非字符串的东西,所以你打印 then 抛出(然后打印)错误。
标签: python python-3.x