Error Handling: The Robot’s Safety Helmet
Protect your Python code from crashes using try and except blocks. Handle ValueErrors and ZeroDivisionErrors gracefully like a pro.
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:
try: Tell the robot: “Try to do this, but be careful!”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.pythonLet’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!")pythonIf 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!")pythonInstead of crashing, the robot displays the warning and keeps running.
Try It Yourself! 🎮#
Open your Python editor and try building a crash-proof calculator:
- Ask the user for a number using
input(). - Try to divide
100by that number. - Write
except ValueErrorto catch text inputs. - Write
except ZeroDivisionErrorto catch zero inputs. - 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! 🪖💻