【问题标题】:In python 3, re-raise an error with a shorter traceback在 python 3 中,使用较短的回溯重新引发错误
【发布时间】:2021-02-21 22:33:44
【问题描述】:

我正在尝试创建一个重新引发任意异常的 try-except 块,但仅包含回溯堆栈中的最后一个块。

类似这样的:

import traceback

def my_func(shorten_tracebacks=True):
    try:
        # Do stuff here

    except Exception as e:
        if shorten_tracebacks:
            raise TheSameTypeOfError, e, traceback.print_exc(limit=1)

        else:
            raise(e)

有没有首选的方法来做到这一点?

如果重要的话,我这样做是为了方便调试 jupyter 笔记本中经常使用的某些 API——它们往往会生成非常长的堆栈跟踪,其中只有最后一个块是有用的。这迫使用户滚动很多。如果不想缩短回溯,可以随时设置shorten_tracebacks=False

【问题讨论】:

  • 阿门。并在我对自己的代码感兴趣的任何异常随附的 unittest/pytest/django crud 的上一层进行核对。 FWIW,我注意到 pdbpp 调试器似乎通过其hf_hide/unhide 功能剥离了很多帧。

标签: python try-except


【解决方案1】:

我的偏好是create a new exception without a context(如果异常有上下文,python 将同时打印异常和导致该异常的异常,以及导致该异常的异常,等等...)

try:
    ...
except:
    raise Exception("Can't ramistat the foo, is foo installed?") from None

一些最佳实践:

  • 在异常消息中包含相关的调试信息。
  • 使用自定义异常类型,以便调用者可以捕获新异常。
  • 仅捕获您预期的特定错误类型,以便通过扩展回溯处理意外错误。

这种方法的缺点是,如果您的异常捕获过于广泛,您最终可能会抑制对调试异常很重要的有用上下文。另一种模式可能如下所示:

try:
    ...
except Exception as e:
    if "ramistat not found" in e.message:
        # The ramistat is missing. This is a common kind of error.
        # Create a more helpful and shorter message
        raise Exception("Can't ramistat the foo, is foo installed?") from None
    else:
        # Some other kind of problem
        raise e

基本上,您检查异常,如果它是一种您知道如何处理的错误,则将其替换为自定义消息。否则,您重新引发原始异常,并让用户弄清楚该怎么做。

【讨论】:

  • 我明白了你的目的,我已经使用相同的模式进行许多其他错误处理。在这种情况下,我的目标不同:重新引发相同的错误类型,但使用更短的回溯堆栈。
猜你喜欢
  • 2020-10-26
  • 1970-01-01
  • 2017-08-31
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 2015-08-31
  • 2021-07-14
相关资源
最近更新 更多