📝 Overview
Programs sometimes crash due to unexpected errors — like dividing by zero or receiving the wrong input. In this lesson, you’ll learn how to use try
, except
, and other error handling tools to make your programs safe and stable.
🎯 What You’ll Learn
-
What runtime errors are
-
How to handle errors using
try
andexcept
-
How to use
else
andfinally
blocks -
Real-world examples of error-proof code
⚠️ 1. What is an Error?
Errors in Python are categorized into:
-
Syntax errors: Mistakes in the code structure (e.g., missing
:
) -
Runtime errors: Problems that happen while the program is running (e.g., dividing by 0, inputting letters instead of numbers)
❌ 2. Common Runtime Errors
These errors stop your program unless you handle them.
🧯 3. Handling Errors with try
and except
✅ The try
block runs your main code
✅ If an error happens, the except
block runs instead
🔁 4. else
and finally
(Optional)
-
else
: runs if there was no error -
finally
: always runs, error or not
🧠 5. Why Use Error Handling?
-
Prevents program crashes
-
Makes user experience smoother
-
Helps debug problems more easily
🧪 Practice Task
Ask the user for a number and print its square. If they enter invalid input, show a message.
⚠️ Mini Challenge
Create a login system:
-
Ask for username
-
If it’s empty, print
"Username cannot be blank"
✅ Summary
-
Use
try
andexcept
to catch errors and avoid crashes -
Add
else
to run only if there are no errors -
Use
finally
to always run cleanup code -
Real apps need safe error handling!