blog.dopana

Back

Welcome back, crash tester! 🪖

Imagine you are riding a bicycle. If you hit a bump, you might fall and get hurt. But if you are wearing a Safety Helmet and elbow pads, you can just dust yourself off, giggle, and keep riding!

In Python, when the robot hits a bump (like a bad instruction), it trips and “crashes” (instantly shuts down and shows scary red error text). Today, we will learn how to put a Safety Helmet on our robot using try and except!

The Safety Net (How Error Handling works)#

Error handling is like wrapping risky commands in a protective bubble:

  1. try: Tell the robot: “Try to do this, but be careful!”
  2. except: Tell the robot: “If you trip and get this error, don’t crash! Instead, do this backup plan.”
graph TD
    Start([Start Risky Code]) --> Try{"try: Do action"}
    Try -->|Success| Done([Keep going! No crash])
    Try -->|Trips - Error| Except{"except: Catch with helmet"}
    Except --> Backup["Run backup code (🩹 Giggle & stand up)"]
    Backup --> Done

Slicing the Banana (ValueError)#

Remember when we asked the player for their age and converted it to an integer?

age = int("banana")  # 💥 CRASH! Python cannot turn "banana" into a number.
python

Let’s protect this code with a safety helmet:

try:
    user_input = input("Enter your age: ")
    age = int(user_input)
    print("You are " + str(age) + " years old! 🎉")
except ValueError:
    print("🩹 Oops! That wasn't a number. The robot caught itself!")
python

If you type "ten" instead of 10, the robot won’t crash! It will just print our friendly warning message.

Dividing by Zero (ZeroDivisionError)#

In math, dividing a number by zero is impossible. If you try to do it in Python, the robot panics and crashes:

try:
    cookies = 10
    kids = 0
    share = cookies / kids
except ZeroDivisionError:
    print("🌌 You cannot divide by zero! The universe would collapse!")
python

Instead of crashing, the robot displays the warning and keeps running.

Try It Yourself! 🎮#

Open your Python editor and try building a crash-proof calculator:

  1. Ask the user for a number using input().
  2. Try to divide 100 by that number.
  3. Write except ValueError to catch text inputs.
  4. Write except ZeroDivisionError to catch zero inputs.
  5. Test it by entering words, then 0, and then a real number!

Congratulations! You have added Crash Protection to your developer toolkit. Your programs are now robust and friendly, ready for players to play without breaking them. Keep up the amazing work! 🪖💻

References#