如何在 python 中引发错误时删除其他文本
How to remove additional text while raising an error in python
所以我做了一些随机的东西:
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。可能吗?
你可以处理异常
try-except
子句
在 except
中只打印错误信息。
参见 https://docs.python.org/3/tutorial/errors.html#handling-exceptions
try:
println(1)
except TypeError as err:
print(err)
所以我做了一些随机的东西:
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。可能吗?
你可以处理异常
try-except
子句
在 except
中只打印错误信息。
参见 https://docs.python.org/3/tutorial/errors.html#handling-exceptions
try:
println(1)
except TypeError as err:
print(err)