Geek University

Nest exception handling statements

Sometime, you need to place one exception-handling statement inside another. This process (called nesting) is often used in situations when you want to obtain the right type of user input. For example, if the user enters a non-numeric value instead of a number, you can give the user another chance to enter the right value type. Here is an example:

newChance = True

while newChance == True:
    try:
        age = int(input('Enter your age: '))
    except ValueError:
        print ('You have to enter a number!')
        try:
            startOver = int(input('To start over, enter 0. To exit, press any other key. '))
        except:
            print('OK, you do not want to start over, see you soon!')
            newChance = False
        else:
            if startOver == 0:
                newChance = True
            else:
                print('OK, you do not want to start over, see you soon!')
                newChance = False

The code above gives the user a second chance to enter a numeric value. The user can choose whether he wants to enter a new value. If the user enters 0, he will get another chance to enter the right value. If he presses any other key, the while loop will end:

>>>
Enter your age: a
You have to enter a number!
To start over, enter 0. To exit, press any other key. r
OK, you do not want to start over, see you soon!
>>>RESTART
>>> 
Enter your age: a
You have to enter a number!
To start over, enter 0. To exit, press any other key. 0
Enter your age: 21

Subscribe to our Newsletter

Like us on Facebook

Share on Twitter

top
Developed by Signum Soft