所以我做了一些隨機的東西:
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 。是否可以?
uj5u.com熱心網友回復:
您可以使用try-except子句處理例外
并except僅列印錯誤訊息。請參閱https://docs.python.org/3/tutorial/errors.html#handling-exceptions
try:
println(1)
except TypeError as err:
print(err)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/324098.html
