如何追溯函数内引发异常的原因?

时间:2015-08-18 09:01:58

标签: 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')

执行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中的哪条指令抛出了try-except子句捕获的异常?

1 个答案:

答案 0 :(得分:3)

这个怎么样?

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