【问题标题】:Why does my code show traceback even when I catch the exception?为什么即使我捕捉到异常,我的代码也会显示回溯?
【发布时间】:2018-02-08 23:55:51
【问题描述】:

这段代码的行为非常奇怪。我基本上复制了我在另一个代码中使用的try/except 块的格式,因为它在另一个代码上运行良好。然而,在这一个中,我得到了回溯异常消息,我无法真正解释。

    def input_rows_columns():
        try:
            print("How many rows do you want?")
            rows = int(input("Rows: "))
            print("How many columns do you want?")
            columns = int(input("Columns: "))
        except ValueError:
            print("\nPlease insert numbers here\n")

        if rows <= 0 or columns <= 0:
            raise ValueError("\nPlease use numbers greater than zero here\n")

        return rows, columns


    def main():
        print("This program will make a barn for you")

        rows, columns = input_rows_columns()

        print(rows)
        print(columns)

    if __name__ == '__main__':
        main()

Here is an image of the traceback when you input zero:

Here is an image of the traceback when you input a string:

很抱歉,如果有更好的方法来追溯,这是我能想到的最好的方法

也许值得一提的是,当他在main() 中调用函数时,第一个程序(我从中复制格式的那个程序)还有另一个try/except

    def main():
        print("This program will calculate the volume of a rectangular box given \
            its lenght, width, and height.\n")

        success = False
        try:
            # get_dimensions() has similar structure as the input_rows_columns() from the program above
            lenght, width, height = get_dimensions('Length', 'Width', 'Height')
            success = True
        except ValueError as e:
            print(e)
        except KeyboardInterrupt:
            print("\nGoodbye.")

        # success = True ficou implícito
        if success:
            volume = lenght * width * height
            print("\nThe volume of the box is %.2f." % volume)


    if __name__ == "__main__":
        main()

但是,当我将这个概念引入上层程序时,它并没有解决问题。

【问题讨论】:

  • 对于第一个屏幕截图,您提出了自己的 ValueError 并且没有捕获它。对于第二个,您永远不会设置 rows 因为会引发错误,因此您需要在 except 块中设置它。
  • 请不要发布代码/数据的图像 - 只需复制并粘贴 Traceback 并将其格式化为代码。
  • 抱歉发了traceback的图片,我就是不知道怎么用文字捕捉,下次我会做的更好

标签: python exception traceback


【解决方案1】:

这都与捕获错误与抛出(引发)错误的位置有关。

如果您不raise 捕获到的 ValueError,代码将继续沿实际未定义行的路径前进。

你在哪里:

int(input("Rows: "))

...此代码在分配rows 之前执行,因此如果这会引发ValueError,它会冒泡到您的except ValueError 行。现在您处于未分配rows 的状态。

如果您想在遇到此错误后停止程序,您可以简单地raise 或致电sys.exit()

except ValueError:
    print("\nPlease insert numbers here\n")
    raise

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 2022-06-15
    • 1970-01-01
    • 2021-06-19
    • 2016-01-24
    • 1970-01-01
    • 2014-03-08
    • 2011-05-05
    • 1970-01-01
    相关资源
    最近更新 更多