Use the else block

EasyException Handling Programs · 7 of 20

Write a Python program that uses else to run code only when no exception occurred.

Advertisement
Input
"25", "x"
Output
25 squared is 625
x is not a number

Approach

  1. else runs after try only if nothing was raised.

Solution

Python
for text in ["25", "x"]:    try:        n = int(text)    except ValueError:        print(text, "is not a number")    else:        print(text, "squared is", n * n)
Output
25 squared is 625
x is not a number

Line by line

Lines 6-7

Keeping the follow-up work in else means a bug there is not hidden by the except.

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment