【问题标题】:How to remove the "Traceback most recent call last" in Python when raising an exception?引发异常时如何在 Python 中删除“Traceback most recent call last”?
【发布时间】:2020-07-20 21:40:06
【问题描述】:

我正在创建一个需要使用 OS 模块的 Python 程序,并且我想自定义报告错误消息。我正在使用 try 和 except 来完成此操作:

try:
    os.mkdir(name)
except FileExistsError:
    raise FileExistsError(name + "\n" + "                        ^ The directory you specified already exists.")

但是,我想删除

Traceback (most recent call last):
  File "file.py", line 20, in <module>
    raise FileExistsError(name + "\n" + "                        ^ The directory you specified already exists.")

部分以便在我每次引发异常时都不会打印引发此异常的代码。

我该怎么做呢?

【问题讨论】:

  • 如果未处理接收,则打印此信息。您需要处理异常,即在 except 块中捕获它并对其进行处理。你只是提出了一个新的异常,然后不处理。
  • 您可以设置sys.tracebacklimit = 0,或使用sys.excepthook 忽略回溯本身。有关详细信息,请参阅here
  • Zvone 是对的。如果您不想看到它,为什么要提出错误。因此,您正在捕获错误,然后作为响应引发相同的错误。如果您想捕获错误,则将您的字符串打印到控制台而不回溯到控制台中,然后摆脱 raise 并在 except FileExistsError 之后使用 print(“string”)。

标签: python try-except python-os


【解决方案1】:

大多数命令行程序的做法是在您与用户交互的程序顶部附近捕获异常,并以对他们有用的形式将其打印出来:

def makedir(name):
    try:
        os.mkdir(name)
    except FileExistsError:
        raise FileExistsError(
            name + "\n" + "^ The directory you specified already exists."
        )


def main():
    try:
        makedir("/tmp")
    except FileExistsError as e:
        print("OOOPS", e)
        return

如果您在顶部捕获的异常类过于宽泛,则会损害您自己的调试能力和用户向您提供精确错误消息的能力,因此您应该精确。事实上,您可能想像这样发明自己的异常类:

class MyAppExceptions(Exception):
    pass


class MyAppFileExists(MyAppExceptions):
    pass


def makedir(name):
    try:
        os.mkdir(name)
    except FileExistsError:
        raise MyAppFileExists(
            name + "\n" + "^ The directory you specified already exists."
        )


def main():
    try:
        makedir("/tmp")
    except MyAppFileExists as e:
        print("OOOPS", e)
        return

然后,如果您的程序由于您未预料到的原因而收到 FileExistsError,您仍将获得可用于调试的异常回溯。

【讨论】:

    【解决方案2】:

    如果你想忽略 full 回溯,有一个简单的方法:

    try:
        ...
    except FileExistsError as e:
        raise MyAppFileExists('message').with_traceback(None) from None
    

    如果你想只删除最后一部分,那就有点难了:

    try:
        ...
    except FileExistsError:
        try:
            raise MyAppFileExists('message')
        except MyAppFileExists as e:
            tb=e.__traceback__
            next_tb=tb
            while next_tb.tb_next.tb_next is not None:
                next_tb=next_tb.tb_next
            next_tb.tb_next=None
            raise e.with_traceback(tb) from None 
    

    from None 表示 Python 不应该打印During handling of the above exception, another exception occurred:。如果您希望发生这种情况,只需删除 from None 部分

    【讨论】:

      猜你喜欢
      • 2022-12-07
      • 2017-12-27
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 2023-01-07
      • 2014-02-14
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多