You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python try-except异常捕获不当 无法修改骑士名称触发重试

Python try-except误触发、骑士名称修改失败问题修复

问题根因

  • 你用了无指定类型的裸except:,会捕获try块内抛出的所有异常,而不是仅捕获你预期的「输入选项非合法整数导致int()转换失败」的错误。只要try块内任意代码出问题,都会直接触发重试逻辑,真实报错被完全吞掉,根本没法定位。
  • 三个属性的修改逻辑都是对传入参数的[0]索引位赋值,这种操作要求传入的对象必须是可变序列(比如列表)。你能正常修改武器、护甲,说明传入的weapon、armour是列表类型,但knights被你传成了字符串——字符串是不可变类型,执行knights[0] = 新名称时会抛出TypeError: 'str' object does not support item assignment,这个异常被裸except捕获,就直接输出重试提示。
  • 用递归做重试逻辑是坏实践,输入错误次数多了会触发递归深度溢出导致程序崩溃。

修复方案

  1. 去掉裸except,明确指定仅捕获ValueError(即int()转换输入失败的场景),其他类型的异常正常抛出,方便排查问题。
  2. 检查函数调用处的传参,确保knights和另外两个参数一致,是列表类型(比如之前如果写knights = "高文",要改成knights = ["高文"]),支持索引位赋值。
  3. 把递归重试改成while循环,避免递归栈溢出问题。
  4. input()本身返回字符串类型,不需要额外套str()做转换。

修复后代码

def update_data(knights, weapon, armour):
    while True:
        print("What would you like to update ?")
        print("1: Knights name: " + knights[0])
        print("2: Weapon: " + weapon[0])
        print("3: Armour: " + armour[0])
        
        try:   
            selection = int(input("Select your Option: "))
            if selection == 1:
                knights[0] = input("what is their new name ? " + knights[0])
                print("Your Knights new name is: " + knights[0])
                break
            elif selection == 2:
                weapon[0] = input("What is their new weapon ? " + weapon[0])
                print("They are now armed with: " + weapon[0])
                break
            elif selection == 3:
                armour[0] = input("What new armour shall they wear ? " + armour[0])
                print("They are now wearing: " + armour[0])
                break
            else:
                print("请输入1-3范围内的有效选项")
        except ValueError:
            print("---Try Again---")

内容的提问来源于stack exchange,提问作者BLVMF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 21:27:19