Python的try-except为何无法抑制错误?仍抛出Traceback问题
问题:try-except未抑制Traceback,字符串与整数比较报错
尝试确保用户输入数值而非字符串,原本以为try-except能捕获并抑制错误,但程序仍抛出Traceback。
程序输出
# python conversion.py Select conversion type, 1) inches to mm 2) mm to inches -1 Invalid response. Select conversion type, 1) inches to mm 2) mm to inches g Invalid response. Select conversion type, 1) inches to mm 2) mm to inches 1 Please specify inches in decimal to convert to mm 1 1.0 inches is equal to 25.4 mm Traceback (most recent call last): File "/home/mcolombo/conversion.py", line 67, in <module> select_conversion() File "/home/mcolombo/conversion.py", line 58, in select_conversion select_conversion() File "/home/mcolombo/conversion.py", line 56, in select_conversion if conversion_type < 1: TypeError: '<' not supported between instances of 'str' and 'int'
错误代码片段
def select_conversion(): conversion_type=input("Select conversion type, 1) inches to mm 2) mm to inches ") try: # checks if input is numeric conversion_type = int(conversion_type) except: print("Invalid response. ") pass select_conversion() if conversion_type < 1: print("Invalid response. ") select_conversion() elif int(conversion_type) > 2: print("Invalid response. ") select_conversion() elif int(conversion_type) == 1: in_mm() else: mm_in()
问题原因
当用户输入非数字内容(如"g"),try块转换int失败进入except,执行递归调用select_conversion()后,原函数的代码会继续执行第56行的判断。此时conversion_type仍是字符串类型,和整数1比较触发TypeError,而这个判断不在try-except范围内,因此抛出Traceback。
解决方案
方案1:递归调用后立即返回
修改except块,在递归调用后添加return,终止当前函数的后续代码执行:
def select_conversion(): conversion_type=input("Select conversion type, 1) inches to mm 2) mm to inches ") try: # checks if input is numeric conversion_type = int(conversion_type) except ValueError: # 明确捕获转换失败的异常,避免捕获其他意外错误 print("Invalid response. ") select_conversion() return # 终止当前函数,不再执行后续判断 if conversion_type < 1: print("Invalid response. ") select_conversion() elif conversion_type > 2: print("Invalid response. ") select_conversion() elif conversion_type == 1: in_mm() else: mm_in()
方案2:用循环代替递归(推荐)
递归不适合这种输入校验场景,改用循环逻辑更清晰,也避免递归深度问题:
def select_conversion(): while True: conversion_type = input("Select conversion type, 1) inches to mm 2) mm to inches ") try: conversion_type = int(conversion_type) # 校验数值范围,符合条件则跳出循环 if 1 <= conversion_type <= 2: break print("Invalid response. ") except ValueError: print("Invalid response. ") # 执行对应转换逻辑 if conversion_type == 1: in_mm() else: mm_in()
内容的提问来源于stack exchange,提问作者korbdallas
相关产品推荐
相关产品推荐

