TalentJR

🐍 Python for kids · Class 5 · Lesson 16 of 18 · Free

Error Handling – try and except

⏱ About 25 minutes · ▶ run real Python here — nothing to install · no sign-in

In this lesson you will

  • Catch an error with try and except, so the program keeps running.
  • Handle ValueError and ZeroDivisionError with friendly messages.
  • Use a loop to ask again until the user types a correct answer.

A good wicketkeeper stands ready behind the stumps. If the batter misses, the keeper catches the ball before it runs away. In this lesson, you will teach Python to catch errors before they crash your program.

What is an error in Python?

Some mistakes only appear while the program runs. For example, int("ten") fails, because "ten" is not written in digits.

When this happens, Python stops and shows a red message like ValueError. This kind of runtime error is called an exception.

Users often type unexpected things. A good program expects this and stays calm, instead of crashing.

The code below works, because "42" is made of digits. Read it, and imagine what "forty two" would do.

🐍 Python — you can edit this code
Output
Next year you will be 43

💡 Common exceptions: ValueError (wrong kind of value), ZeroDivisionError (dividing by 0), NameError (unknown name).

How does try and except work?

Put the risky lines inside try. If one of them fails, Python jumps straight to the except block.

The program does not crash. It runs the except block and then carries on with the next lines.

Here, the user types "ten" instead of 10. Watch where Python jumps.

🎬 How Python thinks — step 1 of 6Python is about to run line 1
▶try:
2 runs = int(input("Runs scored: "))
3 print("Great! You scored", runs)
4except ValueError:
5 print("Please type the runs in digits, like 45.")
6print("Scoreboard updated.")
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Runs scored: ten
Please type the runs in digits, like 45.
Scoreboard updated.

💡 The line after the failing line inside try is skipped. Python leaves try at the moment of the error.

How do I catch different kinds of errors?

One try can have many except blocks, one for each kind of error. Python runs only the block that matches.

Dividing by zero is impossible, so Python raises ZeroDivisionError. Here, someone wants to share 20 laddoos among 0 friends.

🎬 How Python thinks — step 1 of 8Python is about to run line 1
▶try:
2 laddoos = int(input("How many laddoos? "))
3 friends = int(input("How many friends? "))
4 print("Each friend gets", laddoos // friends)
5except ValueError:
6 print("Please type whole numbers only.")
7except ZeroDivisionError:
8 print("You need at least one friend to share with!")
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
How many laddoos? 20
How many friends? 0
You need at least one friend to share with!

What do else and finally do?

else runs only when the try block worked with no error. Put the "success" lines there.

finally runs every time, error or no error. It is good for a closing message, like "Thank you".

Both are optional. Many programs use only try and except.

🐍 Python — you can edit this code
Output
Price of a pencil: 8
5 pencils cost 40 rupees
Thank you for shopping!

How do I keep asking until the answer is right?

Catching an error is good. Asking again is even better! We put try and except inside a while True loop.

If int() works, break leaves the loop. If it fails, except prints a hint and the loop asks again.

The inputs below are "twelve", then "12.5", then "12". Only the last one is a whole number.

🎬 How Python thinks — step 1 of 16Python is about to run line 1
▶while True:
2 try:
3 age = int(input("Your age: "))
4 break
5 except ValueError:
6 print("Digits only, please. Try again.")
7print("Thanks! You are", age, "years old.")
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Your age: twelve
Digits only, please. Try again.
Your age: 12.5
Digits only, please. Try again.
Your age: 12
Thanks! You are 12 years old.

Can I put try and except inside a function?

Yes, and it is very useful. Write the ask-again loop once in a function. Then use it for every number you need.

The function returns the good number, so the rest of the program never sees a bad value.

🐍 Python — you can edit this code
Output
Maths marks: ninety
Please type a number.
Maths marks: 90
Science marks: 85
Total: 175

🤔 Predict the output

Think like Python: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

try:
    x = int("abc")
    print("A")
except ValueError:
    print("B")
print("C")

Question 2. What does this print?

try:
    print(10 / 0)
except ValueError:
    print("Value")
except ZeroDivisionError:
    print("Zero")

Question 3. What does this print?

try:
    n = int("7")
except ValueError:
    print("Bad")
else:
    print("Good", n)
finally:
    print("End")

🧩 Your challenge

Write a safe average calculator. Ask for total marks and the number of subjects. Catch a ValueError (not a number) and a ZeroDivisionError (0 subjects) with friendly messages. The inputs typed for you are 450 and 0.

Expected output (with the inputs given):
Total marks: 450
Number of subjects: 0
Number of subjects cannot be 0.
🐍 Python — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

try:
    print(100 / 0)
except ValueError:
    print("Cannot divide by zero!")

ZeroDivisionError: division by zero

✅ Right

try:
    print(100 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero!")

except only catches the error type you name, so name the error that really happens.

❌ Wrong

age = int(input("Age: "))
try:
    print("You are", age)
except ValueError:
    print("Digits only!")

ValueError: invalid literal for int() with base 10: 'eleven'

✅ Right

try:
    age = int(input("Age: "))
    print("You are", age)
except ValueError:
    print("Digits only!")

The risky line must be inside try, or the error happens before Python is ready to catch it.

❌ Wrong

try:
    marks = int("95")
print("Marks:", marks)

SyntaxError: expected 'except' or 'finally' block

✅ Right

try:
    marks = int("95")
except ValueError:
    marks = 0
print("Marks:", marks)

A try block must always be followed by an except or a finally block.

📌 Remember

  • An exception is an error that happens while the program runs.
  • Put risky lines in try; if one fails, Python jumps to the matching except.
  • ValueError means a wrong kind of value; ZeroDivisionError means dividing by 0.
  • else runs only when there was no error; finally runs every time.
  • Put try and except inside while True, and break when the answer is good.
  • Show friendly messages that tell the user what to type instead.

Finished the quiz and the challenge?

Questions students ask

What is the difference between an error and an exception?

An exception is an error that happens while the program is running, like dividing by zero. Python lets you catch exceptions with try and except. A SyntaxError, like a missing colon, cannot be caught this way; you must fix the code.

Can I write except without an error name?

Yes, but it is not a good habit. It catches every error, even your own typing mistakes, so bugs hide. Name the error you expect, like except ValueError.

Why does int("12.5") give a ValueError?

int() only understands whole numbers written in digits. "12.5" has a decimal point, so it is not a whole number. Use float() if you want decimals.

Do I need else and finally every time?

No. Both are optional. Most of the time, try and except are enough.