【发布时间】: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