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

2024-09-30 16:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

(这是帖子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子句捕获的异常?你知道吗


Tags: thetopystringifscriptfloatprocess
1条回答
网友
1楼 · 发布于 2024-09-30 16:40:29

这个怎么样?你知道吗

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

相关问题 更多 >