TalentJR

🐍 Python for kids · Class 7 · Lesson 17 of 18 · Free

Exception Handling – Catch Errors with try and except

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

In this lesson you will

  • Catch errors with try and except so a program does not crash.
  • Handle different error types, and use else and finally.
  • Raise your own error when data breaks a rule.

A user types "ten" when your program asks for their age. Crash! A red error appears and the program dies. Good programs expect mistakes and handle them politely. Today you learn how.

What is an exception in Python?

An exception is an error that happens while the program runs. Python stops and shows its name, like ValueError.

You have met many already: ValueError, IndexError, KeyError, ZeroDivisionError and FileNotFoundError.

The name tells you what went wrong. ValueError means the type is right but the value makes no sense.

🐍 Python — you can edit this code
Output
Age is 12
Last mark: 91
Half of 10 is 5

💡 Now break it on purpose: change "12" to "twelve", marks[1] to marks[5], or 2 to 0. Read the last line of each error.

How do try and except work in Python?

Put risky code inside a try block. If an error happens there, Python jumps to the except block.

The program does not crash. It runs your except code and then carries on after it.

If no error happens, the except block is simply skipped.

🎬 How Python thinks — step 1 of 7Python is about to run line 1
▶text = input("How many laddoos? ")
2try:
3 count = int(text)
4 print("You ordered", count, "laddoos.")
5except ValueError:
6 print("Please type a number, like 6.")
7print("Thank you for shopping!")
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
How many laddoos? six
Please type a number, like 6.
Thank you for shopping!

💡 Change the input to 6 and run again. This time the except block is skipped.

How do I handle more than one type of error?

One try can have several except blocks. Python runs the first one whose name matches the error.

This lets you give a helpful message for each problem.

Below, the user shares a pizza. Typing 0 friends gives ZeroDivisionError, and a word gives ValueError.

🐍 Python — you can edit this code
Output
4 friends get 2 slices each
0 friends? Nobody to share with!
two is not a number.

What do else and finally do in try except?

else runs only when the try block had no error. It keeps the success code apart from the risky code.

finally runs every time, error or not. It is used for clean-up jobs, like closing files or saying goodbye.

except ... as e stores the error, so you can print Python's own message.

🎬 How Python thinks — step 1 of 14Python is about to run line 1
▶marks = [78, 91, 64]
2for i in [1, 5]:
3 try:
4 m = marks[i]
5 except IndexError as e:
6 print("Error:", e)
7 else:
8 print("Mark found:", m)
9 finally:
10 print("Checked position", i)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Mark found: 91
Checked position 1
Error: list index out of range
Checked position 5

How do I keep asking until the user types a valid number?

Put try and except inside a while True loop. When the input works, break leaves the loop.

When it fails, the except block prints a hint and the loop asks again.

Real apps, like railway booking forms, use this idea to check every box you fill in.

🎬 How Python thinks — step 1 of 11Python is about to run line 1
▶while True:
2 try:
3 seats = int(input("Seats to book (1-6): "))
4 break
5 except ValueError:
6 print("Digits only, please.")
7print("Booking", seats, "seats.")
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Seats to book (1-6): abc
Digits only, please.
Seats to book (1-6): 4
Booking 4 seats.

How do I raise my own error in Python?

Sometimes the value is a valid number but breaks a rule. Marks of 120 out of 100 is one example.

raise ValueError("message") creates your own error. The caller can catch it like any other.

This keeps the checking inside the function, so every part of the program gets the same rule.

🐍 Python — you can edit this code
Output
Saved: 85
Rejected: 120 is not between 0 and 100

🤔 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:
    print("A")
    x = 10 / 0
    print("B")
except ZeroDivisionError:
    print("C")
print("D")

Question 2. What does this print?

try:
    n = int("25")
except ValueError:
    print("bad")
else:
    print("good", n)
finally:
    print("done")

Question 3. What does this print?

data = {"Asha": 88}
try:
    print(data["Ravi"])
except IndexError:
    print("index")
except KeyError:
    print("key")

🧩 Your challenge

Build a safe calculator for dividing a bill. Ask for the bill amount and the number of friends. Keep asking until both are whole numbers and friends is not zero. Then print each person's share using //.

Expected output (with the inputs given):
Bill amount: 600
Number of friends: zero
Please type whole numbers only.
Bill amount: 600
Number of friends: 0
Friends cannot be zero.
Bill amount: 600
Number of friends: 4
Each person pays: 150
🐍 Python — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

try:
    n = int("hello")
except ZeroDivisionError:
    print("Not a number!")

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

✅ Right

try:
    n = int("hello")
except ValueError:
    print("Not a number!")

except only catches the error type it names. int("hello") raises ValueError, so ZeroDivisionError does not catch it.

❌ Wrong

try:
    age = int(input("Age: "))
except ValueError:
    print("That is not a number.")
print("Next year you will be", age + 1)

NameError: name 'age' is not defined

✅ Right

try:
    age = int(input("Age: "))
    print("Next year you will be", age + 1)
except ValueError:
    print("That is not a number.")

When int() fails, age is never created. Code that needs age must go inside try, or in else.

❌ Wrong

marks = [80, 90]
try:
    print("Third mark:", marks[2])
except:
    print("Something went wrong")

No error message – but the message hides the real problem, so you cannot tell what to fix.

✅ Right

marks = [80, 90]
try:
    print("Third mark:", marks[2])
except IndexError as e:
    print("No such mark:", e)

A bare except catches every error, even your own typos. Name the error you expect and print its message.

📌 Remember

  • An exception is an error while the program runs, like ValueError or KeyError.
  • try holds risky code; except runs only if that named error happens.
  • Use several except blocks to give a clear message for each error type.
  • else runs when there was no error; finally runs every time.
  • while True with try, except and break keeps asking until input is valid.
  • raise ValueError("message") creates your own error when a rule is broken.

Finished the quiz and the challenge?

Questions students ask

Should I put my whole program inside try?

No. Keep try blocks small, around the lines that can fail. Then you know exactly which error you are catching.

What is the difference between a syntax error and an exception?

A SyntaxError means Python cannot even read the code, so try cannot help. Exceptions happen while correct code runs.

Can one except catch two error types?

Yes. Write them in a tuple, like except (ValueError, ZeroDivisionError):. Both are handled by the same block.

Is it bad to see errors while coding?

Not at all. Error messages are clues. Read the last line first: it names the error and often the cause.