简体   繁体   中英

If an exception is raised ask again for input

What I'm trying to do is ask the users for two inputs then it call's a function on the inputs but if the result of it raises an exception than ask the user for the inputs again.

This is what I have so far:

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

But the problem with what I have so far is that as it raises that error from the function it stop's everything and doesn't ask the user for inputs again. I was wondering what can I do to fix this.

You don't check for exceptions by comparing equality to exception classes. You use try..except blocks instead

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

Raise an exception isn't the same thing than returning a value. An exception can be caught only with a try/except block:

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

The logic here is to break the infinite loop when we have succeed to complete the add_input call without throwing Illegal exception. Otherwise, it'll re-ask inputs and try again.

If you want to raise an exception in your function you'll need a try/except in your loop. Here's a method that doesn't use a 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")

Recursion could be one way to do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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