指定错误类型时如何打印异常?

2024-10-04 07:35:53 发布

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

我试图显示一个用户友好的错误消息,同时也显示异常,但我似乎无法使它工作。你知道吗

我尝试了这些,但出现了无效的语法错误:

#First try:
except Exception as e, ValueError:
        print("\nThe program is unable to calculate the given equation. " +
            "Try Again!")
        print("\nError message " + e)
        continue

#Second try:
except ValueError, Exception as e:
        print("\nThe program is unable to calculate the given equation. " +
            "Try Again!")
        print("\nError message " + e)
        continue

如果有人能帮我解决这个问题就太好了。谢谢!你知道吗


Tags: thetoisasexceptionprogramgivenprint
1条回答
网友
1楼 · 发布于 2024-10-04 07:35:53

您可以使用回溯:

import traceback

#First try:
except ValueError:
        print("\nThe program is unable to calculate the given equation. " +
            "Try Again!")
        print("\nError message " + traceback.format_exc())
        continue

#Second try:
except Exception as e:
        print("\nThe program is unable to calculate the given equation. " +
            "Try Again!")
        print("\nError message " + traceback.format_exc())
        continue

相关问题 更多 >