(這是一個後續問題到柱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')
在的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
請問是否有方法讓traceback.print_exc()
也在終端窗口打印if-main裏面的哪個指令拋出了ca除了try-except從句嗎?
只需在'if'裏面放置'try' /'except'而不是在函數內部。異常點在於它們傳回給調用者,以便它們可以由知道如何處理它們的圖層來處理。 –
假設您在docstring中指定參數必須是可以轉換爲'float'*爲什麼不使用'float()'?然後,正如@MarkReed所說的那樣,在你調用函數的地方捕獲錯誤。 – jonrsharpe