Lesson 16
Error Handling
Handle errors gracefully
1Try-Except Blocks✨
💻 code
try:
age = int(input("Age: "))
print(f"You're {age} years old")
except ValueError:
print("Please enter a number!")2Multiple Exceptions🎯
💻 code
try:
numbers = [1, 2, 3]
print(numbers[10])
except IndexError:
print("That index doesn't exist!")
except Exception:
print("Something went wrong!")3Finally Block💡
💻 code
try:
file = open("data.txt")
data = file.read()
finally:
file.close() # Always runs4Common Errors🚀
- ValueError - wrong type conversion
- IndexError - list index out of range
- KeyError - dictionary key not found
- NameError - variable not defined
- ZeroDivisionError - dividing by zero
5Preventing Errors🔍
💻 code
def safe_divide(a, b):
if b == 0:
return None
return a / b💻 code
# Validate input
while True:
try:
age = int(input("Age: "))
if age < 0:
print("Age can't be negative!")
continue
break
except ValueError:
print("Please enter a number!")🎯 Practice Challenges
Master Error Handling by completing all 3 difficulty levels
🟢 EASY
Error Handling - Easy Challenge
Start with the basics. Perfect for beginners!
🟡 MEDIUM
Error Handling - Medium Challenge
Get more challenging. Build your confidence!
🔴 HARD
Error Handling - Hard Challenge
Master this concept. Prove your skills!
🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →
Ready to Master Error Handling? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 15: Problem Solving with FunctionsBuild complex programs using functions
- Next lesson →Lesson 17: Working with FilesRead and write files
- Grade 6 coursePython Control FlowPython coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 5 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.