Python如何在没有路径的情况下引发错误



我尝试在没有或路径短的情况下引发错误。

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!

,但在这种情况下,错误并不是函数中的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!

谢谢你的帮助

首先,我认为这里的path指的是我们通常所说的traceback,即从发生错误的点开始将堆栈展开。

没有办法让回溯本身指向错误产生的行以外的任何地方(因为这会太令人困惑:它通常应该指向哪一行?)但是提供更有用的错误消息的约定,我认为这是这里真正的问题:

raise ValueError(f"Stringtester failed on input {integer}, which is not an integer")

这样,尽管用户被带到raise行,但他们知道为什么会引发错误。

顺便说一句,当你把raise语句当作一个"错误"时,你可能会觉得奇怪(毕竟,它正在做它应该做的事情——引发一个错误!),它很快就会看起来很正常:大多数(所有?)语言都这样做。

相关内容

最新更新