2015-08-18 28 views
2

(這是一個後續問題到柱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從句嗎?

+3

只需在'if'裏面放置'try' /'except'而不是在函數內部。異常點在於它們傳回給調用者,以便它們可以由知道如何處理它們的圖層來處理。 –

+0

假設您在docstring中指定參數必須是可以轉換爲'float'*爲什麼不使用'float()'?然後,正如@MarkReed所說的那樣,在你調用函數的地方捕獲錯誤。 – jonrsharpe

回答

2

這是怎麼回事?

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() 
+1

同意,回溯模塊只能從它被調用的地方捕獲。 – Joop

+1

感謝大家的評論 - 我接受了所提供的答案。 – A1dvnp