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. Th
Solution 1:
You don't check for exceptions by comparing equality to exception classes. You use try..except
blocks instead
whileTrue: # keep looping until `break` statement is reached
first_input = input("First number: ")
second_input = input("Second number: ") # <-- only one input linetry: # get ready to catch exceptions inside here
add_input(int(first_input), int(second_input))
except Illegal: # <-- exception. handle it. loops because of while Trueprint("illegal, let's try that again")
else: # <-- no exception. breakbreak
Solution 2:
Raise an exception isn't the same thing than returning a value. An exception can be caught only with a try/except
block:
whileTrue:
first_input = input("First number: ")
second_input = input("Second number: ")
try:
add_input(int(first_input), int(second_input))
breakexcept ValueError:
print("You have to enter numbers") # Catch int() exceptionexcept 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.
Solution 3:
defGetInput():
whileTrue:
try:
return add_input(float(input("First Number:")),float(input("2nd Number:")))
except ValueError: #they didnt enter numbersprint ("Illegal input please enter numbers!!!")
except Illegal: #your custom error was raisedprint ("illegal they must sum less than 10")
Solution 4:
Recursion could be one way to do it:
classIllegalException(Exception):
passdefadd_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()
Solution 5:
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()
defadd_input(first_input, second_input):
if first_input + second_input >= 10:
print('legal')
# Explicitly returning None for clarityreturnNoneelse:
return illegal
whileTrue:
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
Post a Comment for "If An Exception Is Raised Ask Again For Input"