Geek University

The try…except…else statements

You can include an else clause when catching exceptions with a try statement. The statements inside the else block will be executed only if the code inside the try block doesn’t generate an exception. Here is the syntax:

try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
else:
    statements # statements that will be executed if there is no exception

Here is an example:

try:
    age=int(input('Enter your age: '))
except:
    print ('You have entered an invalid value.')
else:
    if age <= 21:
        print('You are not allowed to enter, you are too young.')
    else:
        print('Welcome, you are old enough.')

The output:

>>> 
Enter your age: a
You have entered an invalid value.
>>> RESTART
>>> 
Enter your age: 25
Welcome, you are old enough.
>>>RESTART
>>> 
Enter your age: 13
You are not allowed to enter, you are too young.
>>>

As you can see from the output above, if the user enters a non-numeric value (in this case the letter a) the statement inside the except code block will be executed. If the user enters a numeric value, the statements inside the else code block will be executed.

Subscribe to our Newsletter

Like us on Facebook

Share on Twitter

top
Developed by Signum Soft