我正在做一些Python教程,试图尽可能多地学习语言,我遇到了一些异常处理问题。我正在使用Python 3.4.3
在Windows 10中的cmd中运行代码。具体来说,按下Ctrl + C时,KeyboardInterrupt
块根本不打印任何内容。虽然这不一定重要,但我想到的时候我可能需要在KeyboardInterrupt
上执行其他操作,例如写出文件。
def process_input(input_value):
try:
float_value = float(input_value)
except ValueError:
raise ValueError("\n'%s' is not a number." % input_value)
if float_value <= 0:
raise ValueError("\nMeasurements must be positive values.")
return float_value
def get_dims(*names):
dims = []
for n in names:
raw_input = input("Please enter a %s : " % n)
processed_input = process_input(raw_input)
dims.append(processed_input)
return dims
def main():
print("\nThis program will request a length, width, and height and\n will" \
"return the total volume for a box.\n")
success = False
try:
length, width, height = get_dims('Length', 'Width', 'Height')
success = True
except ValueError as e:
print(e)
except KeyboardInterrupt:
print("\nInterrupted.")
if success:
volume = length * width * height
print("\nThe volume of the box is %.2f" % volume)
if __name__ == '__main__':
main()
在按下Ctrl + C期间,而不是打印出消息&#34; Interrupted&#34;
第一个用户输入,输出如下:
Please enter a Length : Traceback (most recent call last):
我在Windows 10中,在cmd中运行代码。有什么想法吗?