
🐍 Lesson 12: Python Error Handling (Try...Except)
1. What is error handling?
In short → Errors (exceptions) can happen while Python code runs. Error handling is the practice of managing those errors gracefully so the program doesn't crash and can keep running smoothly.
In detail → Error handling is the process of managing exceptions so that the program doesn't crash and can continue running smoothly.
2. Common Errors in Python
ZeroDivisionError→ divide by zeroValueError→ invalid valueTypeError→ wrong data typeFileNotFoundError→ file not found
3. Summary
✅ Use try...except to handle errors gracefully
✅ Multiple except blocks handle different error types
✅ else runs if no error occurs
✅ finally always runs (cleanup, closing files)
python
# ===== 1. Basic Try...Except =====
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
# ===== 2. Multiple Except Blocks =====
print(f"\n===== Multiple Exceptions =====")
try:
num = int("abc")
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Division by zero")
# ===== 3. Catching Any Exception =====
print(f"\n===== Catch Any Exception =====")
try:
x = 10 / 0
except Exception as e:
print(f"Error occurred: {e}")
# ===== 4. Using else =====
print(f"\n===== Using else =====")
try:
x = 5 / 1
except ZeroDivisionError:
print("Error!")
else:
print(f"Success: {x}")
# ===== 5. Using finally =====
print(f"\n===== Using finally =====")
try:
f = open("data.txt")
content = f.read()
except FileNotFoundError:
print("File not found")
finally:
print("Closing file (if opened)")
# ===== 6. Real-World Example =====
print(f"\n===== Safe Divide Function =====")
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError:
return "Invalid input type"
finally:
print("Division attempted")
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # Cannot divide by zero
print(safe_divide(10, "a")) # Invalid input typeYou should see
You cannot divide by zero! ===== Multiple Exceptions ===== Invalid number ===== Catch Any Exception ===== Error occurred: division by zero ===== Using else ===== Success: 5.0 ===== Using finally ===== File not found Closing file (if opened) ===== Safe Divide Function ===== Division attempted 5.0 Division attempted Cannot divide by zero Division attempted Invalid input type