Answer to Question #207639 in C++ for Sarivinkumar M

Question #207639

Design a program that uses try-catch mechanism to check whether the integer input entered is correct type or not.

Runtime input

ABC

Output



1
Expert's answer
2021-06-17T04:36:27-0400
n = int(input("Please enter a number: "))

With the aid of exception handling, we can write robust code for reading an integer from input:

In [ ]:

while True:
    try:
        n = input("Please enter an integer: ")
        n = int(n)
        break
    except ValueError:
        print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")

It's a loop, which breaks only if a valid integer has been given. The while loop is entered. The code within the try clause will be executed statement by statement. If no exception occurs during the execution, the execution will reach the break statement and the while loop will be left. If an exception occurs, i.e. in the casting of n, the rest of the try block will be skipped and the except clause will be executed. The raised error, in our case a ValueError, has to match one of the names after except. In our example only one, i.e. "ValueError:". After having printed the text of the print statement, the execution does another loop. It starts with a new input().

We could turn the code above into a function, which can be used to have a foolproof input.

def int_input(prompt):
    while True:
        try:
            age = int(input(prompt))
            return age
        except ValueError as e:
            print("Not a proper integer! Try it again")

We use this with our dog age example from the chapter Conditional Statements.

def dog2human_age(dog_age):
    human_age = -1
    if dog_age < 0:
        human_age = -1
    elif dog_age == 0:
        human_age = 0
    elif dog_age == 1:
        human_age = 14
    elif dog_age == 2:
        human_age = 22
    else:
        human_age = 22 + (dog_age -2) * 5
    return human_age
age = int_input("Age of your dog? ")
print("Age of the dog: ", dog2human_age(age))
Not a proper integer! Try it again
Not a proper integer! Try it again
Age of the dog:  37

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS