Python 为什么我的代码在捕获异常时仍显示回溯?
这段代码的行为真的很奇怪。我基本上复制了Python 为什么我的代码在捕获异常时仍显示回溯?,python,exception,traceback,Python,Exception,Traceback,这段代码的行为真的很奇怪。我基本上复制了try/的一种格式,除了我在另一个代码中使用的块,因为它在另一个代码中工作得很好。然而,在这一次中,我得到了回溯和异常消息,我真的无法解释 def input_rows_columns(): try: print("How many rows do you want?") rows = int(input("Rows: ")) print("How many c
try
/的一种格式,除了我在另一个代码中使用的
块,因为它在另一个代码中工作得很好。然而,在这一次中,我得到了回溯和异常消息,我真的无法解释
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()
但是,当我将这个概念引入上层程序时,它并不能解决问题。这都与捕获或抛出错误的位置有关 如果不
提出捕获到的
值错误,代码将沿着未实际定义行的路径继续
如果您有:
int(输入(“行:”)
…此代码在分配行
之前执行,因此如果此操作引发一个ValueError
,它会冒泡到您的行,ValueError除外。现在您处于未分配行
的状态
如果要在出现此错误后停止程序,只需调用raise
或sys.exit()
对于第一个屏幕截图,您提出了自己的ValueError,但没有捕捉到它。对于第二个,您从未设置行
,因为会引发错误,因此您需要在块中设置该行,但
块除外。请不要发布代码/数据的图像-只需复制并粘贴回溯并将其格式化为代码。很抱歉发布回溯图像,我只是不知道如何在文本中捕获,下次我会做得更好
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()
except ValueError:
print("\nPlease insert numbers here\n")
raise