Python Can';t使用用户输入引发异常

Python Can';t使用用户输入引发异常,python,exception-handling,try-catch,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

我正在练习尝试并提出异常,因为我还没有完全掌握如何正确使用它们

当用户输入的选项不在我指定的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")
然而,当我运行它的用户选择将被接受,无论他们键入什么,我不清楚为什么

我知道我可以通过其他方式来实现这一点,比如在原始输入后放置一个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")

请注意,
仅为
打字错误。

我不确定您为什么要将支票放入异常处理程序中。修复它:

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")

请注意,
仅限于
打字错误。

类似Python的错误处理的优点是可以在一个级别检测错误,但可以由另一个级别处理。假设您有一个自定义输入函数,该函数尝试验证输入,并在出现问题时引发几个异常之一。在这里,我们将使用一个自定义异常,但正如建议的那样,使用类似ValueError的内置异常也很好:

class BadChoiceError(Exception):

    def __str__(self):
        return "That choice not available!"

def get_choice(prompt):
    choice = raw_input(prompt)
    if choice not in {'gun', 'grenade', 'smoke bomb'}:
        raise BadChoiceError()
    return choice

inventory = []

print "You can choose 2 items from the following:"
print "Gun, Grenade, Smoke bomb. Type your weapon choices now: " 

try:
    choice1 = get_choice("Choice 1: ")

    inventory.append(choice1)

except BadChoiceError as error:
    print(str(error))
    print("Please enter one of the 3 choices only.")

except:
    exit("Unknown error.  Try again later.")
输入函数可以选择自行处理错误,但它允许更高级别的代码决定处理错误的最佳方式
这种情况(或不是。)

类似Python的错误处理的优点是可以在一个级别上检测到错误,但可以由另一个级别来处理。假设您有一个自定义输入函数,该函数尝试验证输入,并在出现问题时引发几个异常之一。在这里,我们将使用一个自定义异常,但正如建议的那样,使用类似ValueError的内置异常也很好:

class BadChoiceError(Exception):

    def __str__(self):
        return "That choice not available!"

def get_choice(prompt):
    choice = raw_input(prompt)
    if choice not in {'gun', 'grenade', 'smoke bomb'}:
        raise BadChoiceError()
    return choice

inventory = []

print "You can choose 2 items from the following:"
print "Gun, Grenade, Smoke bomb. Type your weapon choices now: " 

try:
    choice1 = get_choice("Choice 1: ")

    inventory.append(choice1)

except BadChoiceError as error:
    print(str(error))
    print("Please enter one of the 3 choices only.")

except:
    exit("Unknown error.  Try again later.")
输入函数可以选择自行处理错误,但它允许更高级别的代码决定处理错误的最佳方式
这种情况(或不是。)

为此,您可以创建自己的自定义异常 ... 使继承异常类的相应类尝试用…捕获异常

class YourException(Exception):
    def __repr__(self):
        return 'invalid choice'
invent = []
try:
    c = raw_input("enter your choice :")
    if c not in ['dvdvdf','vfdv','fvdv']:#these are your choice
        raise YourException()

为此,您可以创建自己的自定义异常 ... 使继承异常类的相应类尝试用…捕获异常

class YourException(Exception):
    def __repr__(self):
        return 'invalid choice'
invent = []
try:
    c = raw_input("enter your choice :")
    if c not in ['dvdvdf','vfdv','fvdv']:#these are your choice
        raise YourException()

若要
引发
异常,您不需要
尝试/例外
。只有在需要捕获异常时才需要
try/except
。要
raise
异常,不需要
try/except
。只有当您需要捕获异常时,才需要
try/except
。我认为在
inventory.append(choice1)
之前引发异常更为合理。好吧,我想我当时对这个主题的理解有点混乱。当我使用您的解决方案时,它是有效的,但当我希望它继续运行(它是大部分代码的一部分)并不断询问用户直到他们选择正确答案时,程序就会结束。我的理解是,这就是它在异常情况下的工作方式。还是我应该使用while循环?@easy\u c0mpany80听起来你不需要实际引发异常,而是打印出选择验证错误,让用户尝试更多。这些是相关的线程:,。我认为在
inventory.append(choice1)
之前引发异常更为合理。好吧,我想我对这个主题的理解是混乱的。当我使用您的解决方案时,它是有效的,但当我希望它继续运行(它是大部分代码的一部分)并不断询问用户直到他们选择正确答案时,程序就会结束。我的理解是,这就是它在异常情况下的工作方式。还是我应该使用while循环?@easy\u c0mpany80听起来你不需要实际引发异常,而是打印出选择验证错误,让用户尝试更多。这些是相关的线程:,。谢谢,这对我来说是有意义的,但对于一个简单的任务来说,似乎有很多代码,这是最好的方法吗?我不能说什么是最好的方法--我相信这种类型的异常处理会在较大的程序中处理错误,因此在较小的程序中可能看起来有点麻烦。但是练习它是一件好事。谢谢,这对我来说很有意义,但是对于一个简单的任务来说,似乎有很多代码,这是最好的方法吗?我不能说什么是最好的方法——我相信这种类型的异常处理会在较大的程序中处理错误,因此在较小的程序中可能看起来有点麻烦。但是练习它是一件好事。