[英]Python how to raise Errors without a path
我嘗試在沒有路徑或短路路徑的情況下引發錯誤。
def stringtester(integer):
if type(integer) != int:
raise ValueError("this is not a integer and I only like integers!")
else:
print("this is a integer and I like integers!")
stringtester("this is a string")
從邏輯上講它會引發錯誤
Traceback (most recent call last):
File "C:/Users/user/Python/test.py", line 7, in <module>
stringtester("this is a string")
File "C:/Users/user/Python/test.py", line 3, in stringtester
raise ValueError("this is not a integer and I only like integers!")
ValueError: this is not a integers and I only like integers!
但在這種情況下,錯誤實際上並不是 function 中的加注。更多的是嘗試使用字符串執行 function。 有沒有辦法修改 raise 發送錯誤的路徑,而沒有像這樣的完整路徑?
Traceback (most recent call last):
File "C:/Users/user/Python/test.py", line 7, in <module>
stringtester("this is a string")
ValueError: this is not a integer and I only like integers!
感謝您的幫助
首先,我認為這里的路徑指的是我們通常所說的traceback ,即從發生錯誤的點展開堆棧。
除了引發錯誤的行之外,沒有辦法讓回溯本身指向任何其他內容(因為那太混亂了:一般來說它應該指向哪一行?)。 但是有一個提供更有用的錯誤消息的約定,我認為這是真正的問題:
raise ValueError(f"Stringtester failed on input {integer}, which is not an integer")
這樣,盡管用戶被帶到raise
線,但他們知道為什么會引發錯誤。
順便說一句,雖然作為“錯誤”被帶到raise
語句中可能會讓您感到奇怪(畢竟,它正在做它應該做的事情——引發錯誤:)它很快就會看起來很正常? 大多數(所有)語言都這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.