假设我有以下脚本:
def do_not_call_on_one(i):
if i == 1:
raise ValueError("You never listen.")
print "Success!"
do_not_call_on_one(1)
执行时,您将看到以下回溯:
Traceback (most recent call last):
File "test.py", line 7, in <module>
do_not_call_on_one(1)
File "test.py", line 3, in do_not_call_on_one
raise ValueError("You never listen.")
ValueError: You never listen.
是否有某种方法可以操纵调用堆栈,以便从实际导致问题的行发出错误,如下所示?:
Traceback (most recent call last):
File "test.py", line 7, in <module>
do_not_call_on_one(1)
ValueError: You never listen.
这将节省开发人员的时间,否则开发人员将浪费时间扫描调用堆栈、搜索错误使用的函数,而可以提前定义正确的行为。
Python 中是否有任何内容允许异常使用修改后的回溯?
Update
有一些程序正在复制此功能:
# In test.py:
int('a')
# Executing 'python test.py' yields:
Traceback (most recent call last):
File "test.py", line 1, in <module>
int('a')
ValueError: invalid literal for int() with base 10: 'a'
Note:回溯不会下降到int()
函数显示一堆无用的范围(尤其是无用的范围)raise ValueError
本身)。