小编kal*_*nov的帖子

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

(这是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", …
Run Code Online (Sandbox Code Playgroud)

python function try-except

5
推荐指数
1
解决办法
262
查看次数

标签 统计

function ×1

python ×1

try-except ×1