Skip to main content
 首页 » 编程设计

python之无法通过用户输入引发异常

2025年05月04日9mate10pro

我正在练习 try 和 raise 异常,因为我还没有完全掌握如何正确使用它们。

当用户输入的选项不在我的 3 个指定选项中时,我想在这段代码中引发异常:

    inventory = [] 
    print "You can choose 2 items from the following:" 
    print "Gun, Grenade, Smoke bomb. Type your weapon choices now: "  
 
    try: 
        choice1 = raw_input("Choice 1:  ") 
        inventory.append(choice1) 
 
    except: 
        if choice1 not in ('gun', 'grenade', 'smoke bomb'): 
            raise Exception("Please enter one of the 3 choices only only") 

然而,当我运行它时,无论用户输入什么,用户的选择都会被接受,我不清楚为什么。

我知道我可以用其他方法来完成这项工作,例如在 raw_input 之后放置一个 while 循环来检查针对这 3 个项目输入的内容,但我想用 try 和 except 来做到这一点。

谢谢

请您参考如下方法:

我不确定为什么要将检查放在异常处理程序中。修复它:

choice1 = raw_input("Choice 1:  ") 
if choice1 not in ('gun', 'grenade', 'smoke bomb'): 
    raise Exception("Please enter one of the 3 choices only only") 

顺便说一下,内置的 ValueError 在这里听起来像是一个合乎逻辑的异常选择:

raise ValueError("Please enter one of the 3 choices only only") 

注意 only only 拼写错误。