Python 如何追溯函数中引发异常的原因?
(这是《华盛顿邮报》的后续问题。) 我有以下Python 如何追溯函数中引发异常的原因?,python,function,try-except,Python,Function,Try Except,(这是《华盛顿邮报》的后续问题。) 我有以下script.py: import traceback def process_string(s): """ INPUT ----- s: string Must be convertable to a float OUTPUT ------ x: float """ # validate that s is convertable to a floa
script.py
:
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertable to a float
OUTPUT
------
x: float
"""
# validate that s is convertable to a float
try:
x = float(s)
return x
except ValueError:
print
traceback.print_exc()
if __name__ == '__main__':
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
执行script.py
后,终端窗口中将打印以下消息:
Traceback (most recent call last):
File "/home/user/Desktop/script.py", line 20, in process_string
x = float(s)
ValueError: could not convert string to float: t01
我想问一下,是否有办法回溯。print_exc()也可以在终端窗口中打印if main中的哪个指令引发了try except子句捕获的异常?这是怎么回事
import traceback
def process_string(s):
"""
INPUT
-----
s: string
Must be convertible to a float
OUTPUT
------
x: float
"""
return float(s)
if __name__ == '__main__':
try:
a = process_string('0.25')
b = process_string('t01')
c = process_string('201')
except ValueError:
print
traceback.print_exc()
只需将
try
/放入if
中,而不是函数中。异常点是它们传播回调用者,这样就可以由知道如何处理它们的层来处理。如果您在docstring中指定参数必须是可以转换为float
的字符串,为什么不直接使用float()
?然后,正如@MarkReed所说,在调用函数的地方捕获错误。同意,回溯模块只从调用它的地方捕获错误。感谢大家的评论,我接受提供的答案。