DAY 20

Error Handling 🛡️⚠️🔧

Stop your program from crashing! Handle problems gracefully so the app keeps running no matter what.

⏱ 15 mins
⚡ +50 XP
Error Handling 🛡️⚠️🔧

Day 20: Error Handling — Programs That Never Crash!

Why Error Handling Matters

Imagine a car without airbags. One small accident and it's over. Now imagine a car with airbags — accident happens, airbags deploy, everyone survives. Error handling is your program's airbag! When something goes wrong, it activates and keeps the program running instead of crashing.

The try and except


try:
    number = int(input("Enter a number: "))
    print(number)
except:
    print("Invalid input!")

try = attempt this code. If it works, great! except = if anything goes wrong, do this instead. User types "abc" instead of a number? No crash — just prints "Invalid input!" and carries on!

Real World Connection

When you enter a wrong OTP on PhonePe, it doesn't crash — it says "Wrong OTP, try again". When you type letters in an age field on a form, it doesn't crash — it says "Please enter a valid age". Every app you use is wrapped in error handling so you never see a crash!

Catching Specific Errors


try:
    age = int(input("Your age: "))
    print("Next year you'll be", age + 1)
except ValueError:
    print("Please type a number, not letters!")
except:
    print("Something went wrong!")

ValueError catches specifically when someone types text where a number is expected. The last except catches anything else. Professional apps catch specific errors to give helpful messages!

Common Mistakes

Mistake 1 — Not using try/except at all.


number = int("abc")   # CRASHES with no warning!

try:
number = int("abc")
except:
print("Invalid!")  # SAFE — handled gracefully!  

Mistake 2 — Wrong indentation inside try or except.


try:
print("Hello")    # WRONG — must be indented!

try:
print("Hello")  # CORRECT  

Mini Challenge

Mini Challenge

Ask the user for two numbers and divide them. Wrap it in try/except. What happens if someone types "abc"? What happens if they try to divide by zero? Handle both! You just built the same safety system every calculator app uses!

Quick Quiz

Q: What does try do? A: Attempts to run the code inside it.

Q: What happens when the code inside try fails? A: Python jumps to except and runs that code instead — no crash!

Q: What error occurs when you do int("abc")? A: ValueError — you tried to convert text to a number!

Key Takeaways

Key Takeaways

  • try runs your code. except catches errors if something goes wrong.
  • Error handling stops crashes — the program recovers and keeps going.
  • ValueError happens when wrong data type is given like int("abc").
  • Always indent code inside try and except.
  • The best programs don't avoid errors — they handle them gracefully!

← Previous Lesson