eas*_*y80 1 python exception-handling try-catch
我练习尝试并提出例外,因为我还没有完全掌握如何正确使用它们.
当用户输入一个不在我指定的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")
Run Code Online (Sandbox Code Playgroud)
然而,当我运行它时,用户的选择将被接受,无论他们输入什么,我不清楚为什么.
我知道我可以通过其他方式来完成这项工作,例如在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")
Run Code Online (Sandbox Code Playgroud)
顺便说一句,内置ValueError声音在这里听起来像一个逻辑异常选择:
raise ValueError("Please enter one of the 3 choices only only")
Run Code Online (Sandbox Code Playgroud)
并注意only only错字.