繁体   English   中英

如果引发异常,请再次输入

[英]If an exception is raised ask again for input

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

这是我到目前为止的内容:

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

但是到目前为止,我所遇到的问题是,由于它从函数中引发了该错误,因此它停止了所有操作,并且不再要求用户再次输入。 我想知道如何解决此问题。

您无需通过将相等性与异常类进行比较来检查异常。 您使用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

引发异常与返回值不是同一回事。 只能使用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调用而不会add_input Illegal异常时,打破无限循环。 否则,它将重新询问输入,然后重试。

如果要在函数中引发异常,则在循环中需要try / except。 这是一种不使用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
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")

递归可能是做到这一点的一种方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM