Skip to content

Python try except else

  • by

You can use the try-except else statement in Python. The try-except has else an optional else clause with the following syntax:

try:
    # code that may cause errors
except:
    # code that handle exceptions
else:
    # code that executes when no exception occurs
  • If an exception occurs in the try clause, it skips the rest of the statements in the try clause and the except statement execute.
  • In case no exception occurs in the try clause, the else clause will execute.

Python try except else example

Simple example code.

def main():
    try:
        height = float(input('Enter your height (meters):'))
        weight = float(input('Enter your weight (kilograms):'))

    except ValueError as error:
        print('Error! please enter a valid number.')
    else:
        bmi = round(weight / height ** 2)
        evaluation = ''
        if 18.5 <= bmi <= 24.9:
            evaluation = 'Healthy'
        elif bmi >= 25:
            evaluation = 'Overweight'
        else:
            evaluation = 'Underweight'

        print(f'Your body mass index is {bmi}')
        print(f'This is considered {evaluation}!')


main()

Output:

Python try except else example

Using Python try…except…else and finally

When you include the finally clause, the else clause executes after the try clause and before the finally clause.

fruits = {
'apple': 10,
'orange': 20,
'banana': 30
}

key = None
while True:
try:
key = input('Enter a key to lookup:')
fruit = fruits[key.lower()]
except KeyError:
print(f'Error! {key} does not exist.')
except KeyboardInterrupt:
break
else:
print(fruit)
finally:
print('Press Ctrl-C to exit.')

Output:

Enter a key to lookup:3
Error! 3 does not exist.
Press Ctrl-C to exit.
Enter a key to lookup:

Do comment if you have any doubts or suggestions on this Python try except the tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading