🛡️ Python Course in 4 to 6 Weeks – Lesson 12: Error Handling in Python
Welcome to Lesson 12 of our Python Course in 4 to 6 Weeks! In this lesson, we’ll learn how to write safer and more stable Python code using error handling techniques. Mistakes happen — and your code needs to handle them gracefully.
✅ What You'll Learn
- What are exceptions and errors?
- Using
try
,except
to handle errors - Using
finally
andelse
blocks - Common Python errors and how to fix them
- Writing custom error messages
🚨 Common Errors in Python
ZeroDivisionError
– dividing by 0ValueError
– invalid input typeTypeError
– mismatched data typesFileNotFoundError
– trying to open a missing file
🧯 Using try-except
try:
x = int(input("Enter a number: "))
result = 10 / x
print("Result:", result)
except ZeroDivisionError:
print("❌ You can't divide by zero!")
except ValueError:
print("❌ Please enter a valid number.")
📌 Using else and finally
try:
f = open("file.txt")
except FileNotFoundError:
print("File not found.")
else:
print("File opened successfully!")
f.close()
finally:
print("This block always runs.")
⚠️ Tips for Safe Coding
- 🔒 Always validate user input
- 💬 Use custom messages to help users understand errors
- 🚫 Don’t leave broad
except:
without specifying the error type
🧪 Practice Challenge
Create a Python file named safe_divider.py
that:
- Asks the user for two numbers
- Tries to divide them
- Handles
ZeroDivisionError
andValueError
- Prints a custom success or failure message
📥 Tools You'll Need
- 🐍 Python: https://www.python.org/downloads/
- 📝 VS Code: https://code.visualstudio.com/
- 🌐 Replit: https://replit.com/languages/python3
📌 Final Words
With error handling, your programs become stronger and more user-friendly. Always remember: good code doesn’t just work — it fails safely. Up next, we’ll cover how to work with Python modules and libraries to use and organize external code.
🔗 Coming Next:
Lesson 13: Modules & Libraries – Organize and Reuse Python Code 📦