如果出现异常,请再次询问输入

时间:2014-02-21 19:54:23

标签: python

我要做的是询问用户输入两个输入,然后调用输入上的函数,但是如果它的结果​​引发异常,则再次询问用户输入。

这是我到目前为止所做的:

class Illegal(Exception):
    pass

def add_input(first_input, second_input):
    if first_input + second_input >= 10:
        print('legal')
    else:
        raise Illegal

first_input = input("First number: ")
second_input = input("Second number: ")
while add_input(int(first_input), int(second_input)) == Illegal:
    print("illegal, let's try that again")
    first_input = input("First number: ")
    second_input = input("Second number: ")

但到目前为止我所遇到的问题是,当它从函数中引发错误时它会停止所有内容并且不会再次要求用户输入。我想知道我该怎么做才能解决这个问题。

5 个答案:

答案 0 :(得分:4)

您不会通过将异常与异常类进行比较来检查异常。您改为使用try..except

while True:              # keep looping until `break` statement is reached
    first_input = input("First number: ")
    second_input = input("Second number: ")   # <-- only one input line
    try:                 # get ready to catch exceptions inside here
        add_input(int(first_input), int(second_input))
    except Illegal:      # <-- exception. handle it. loops because of while True
        print("illegal, let's try that again")
    else:                # <-- no exception. break
        break

答案 1 :(得分:2)

提出异常与返回值不是一回事。只能使用try/except块来捕获异常:

while True:
    first_input = input("First number: ")
    second_input = input("Second number: ")
    try:
        add_input(int(first_input), int(second_input))
        break
    except ValueError:
        print("You have to enter numbers")  # Catch int() exception
    except Illegal:
        print("illegal, let's try that again")

这里的逻辑是在我们成功完成add_input调用而不抛出Illegal异常时打破无限循环。否则,它会重新询问输入并重试。

答案 2 :(得分:0)

如果你想在函数中引发异常,你需要在循环中尝试/除外。这是一种不使用try / except的方法。

illegal = object()

def add_input(first_input, second_input):
    if first_input + second_input >= 10:
        print('legal')
        # Explicitly returning None for clarity
        return None
    else:
        return illegal

while True:
    first_input = input("First number: ")
    second_input = input("Second number: ")
    if add_input(int(first_input), int(second_input)) is illegal:
        print("illegal, let's try that again")
    else:
        break

答案 3 :(得分:0)

def GetInput():
   while True:
        try:
           return add_input(float(input("First Number:")),float(input("2nd Number:")))
        except ValueError: #they didnt enter numbers
           print ("Illegal input please enter numbers!!!")
        except Illegal: #your custom error was raised
           print ("illegal they must sum less than 10")

答案 4 :(得分:0)

递归可能是一种方法:

class IllegalException(Exception):
    pass

def add_input(repeat=False):
    if repeat:
        print "Wrong input, try again"
    first_input = input("First number: ")
    second_input = input("Second number: ")
    try:
        if first_input + second_input >= 10:
            raise IllegalException
    except IllegalException:
        add_input(True)

add_input()