kal*_*nov 5 python function try-except
(这是Python try/ except: Showing the Cause of the error after Displaying my Variables 帖子的后续问题。)
我有以下内容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')
Run Code Online (Sandbox Code Playgroud)
执行后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
Run Code Online (Sandbox Code Playgroud)
请问是否有一种方法可以traceback.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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
262 次 |
| 最近记录: |