Lesson 17
Exception Handling
Handle errors gracefully
1What is Exception Handling?✨
Exception handling is a way to deal with errors in your programs without crashing them. It helps you manage problems gracefully, allowing your program to continue running or to inform the user about what went wrong.
2Why Learn Exception Handling?🎯
- ✓ Prevents program crashes
- ✓ Improves user experience
- ✓ Helps find and fix bugs
- ✓ Essential for real-world applications
3Try and Except💡
The basic way to handle exceptions in Python is using the try and except keywords. You wrap the code that might cause an error in a try block and handle the error in an except block.
4Example:🚀
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("That's not a valid number!")5Common Exceptions🔍
- There are many types of exceptions you might encounter. Here are a few common ones:
- ValueError: Invalid input type
- IndexError: Trying to access an index that doesn’t exist
- KeyError: Accessing a dictionary with a non-existent key
6Example:⭐
my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError:
print("That index does not exist!")7Finally Block🧩
Sometimes, you want to run some code no matter what happens, even if there was an error. You can do this using the finally block.
8Example:🎈
try:
file = open("myfile.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close()9Practice Activity✨
Create a simple calculator that handles input errors. Allow the user to divide two numbers and handle the case when they input zero as the denominator.
10Example:🎯
try:
num1 = float(input("Enter numerator: "))
num2 = float(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("You cannot divide by zero!")🎯 Practice Challenges
Master Exception Handling by completing all 3 difficulty levels
Exception Handling - Easy Challenge
Start with the basics. Perfect for beginners!
Exception Handling - Medium Challenge
Get more challenging. Build your confidence!
Exception 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 Exception Handling? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 16: File Handling BasicsRead and write text files
- Next lesson →Lesson 18: Capstone: Data Analysis ProjectAnalyze a real dataset end-to-end
- Grade 8 courseJavaScript Basics - Web ProgrammingJavaScript coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 7 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.