【问题标题】:How to print out the line of where the exception is coming from [duplicate]如何打印出异常来自的行[重复]
【发布时间】:2021-12-06 10:41:11
【问题描述】:
def println(text: str):
    try:
    print(text)
    if not type(text) == str:
        raise TypeError(f"argument \"text\" should be type \"str\". not type \"{type(text)}\"".)
    except TypeError as err:
         print(err)

这很好用,它说:

argument "text" should be type "str". not type "<class 'int'>".

但我看不出它来自哪条线路。它来自第 4 行,并没有说明错误来自哪一行。这使得调试错误变得困难且令人沮丧。

【问题讨论】:

  • 如果您没有发现错误,解释器会很高兴地向您显示完整的回溯(包括行号)。抛出错误只是为了在同一范围内捕获它似乎不是最好的实现。 print(text) 也能很好地处理非字符串的东西,所以你打印 then 抛出(然后打印)错误。

标签: python python-3.x


【解决方案1】:
import traceback
traceback.print_exc()

将使用解释器用于未捕获异常的相同默认回溯格式。

或者,更好的是,根本不捕获异常并让它在其他地方处理?如果您确实需要包装异常以更改其类型或消息,则可以这样做

except SomeException as exc:
    raise RuntimeError("a thing broke") from exc

这将保留原始异常和回溯。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 2016-01-19
    • 2017-04-05
    相关资源
    最近更新 更多