Error Handling and Exceptions¶
No errors = Junior dev Smart error handling = $150K+ Senior Engineer
Companies TEST: “How do you prevent production crashes?”
🎯 Error Handling = Million Dollar Insurance¶
| Error Type | Without Handling | With Handling | Business Cost |
|---|---|---|---|
| File missing | App crashes | “File not found, using backup” | $10K/hour |
| Bad input | 500 error | “Please enter valid number” | Customer trust |
| Network fail | Dead app | “Retrying in 5s...” | 99.9% uptime |
| Data corrupt | Silent fail | “Alert: Data issue detected” | $1M fraud |
🚀 Step 1: Try/Except = Bulletproof Code¶
## CRASHING CODE vs SAFE CODE (Run this!)
## ❌ JUNIOR: CRASHES
## sales_input = input("Sales: ")
## profit = float(sales_input) * 0.28 # CRASHES on "abc"!
## ✅ SENIOR: BULLETPROOF
def safe_profit_calc(sales_input):
try:
sales = float(sales_input)
if sales < 0:
raise ValueError("Sales cannot be negative!")
return sales * 0.28 - 8000
except ValueError as e:
return f"❌ Input Error: {e}"
except:
return "❌ Unknown error - contact support"
## TEST ALL SCENARIOS
print("🛡️ ERROR HANDLING TEST:")
print(f" Good input: ${safe_profit_calc('35000')}")
print(f" Bad input: {safe_profit_calc('abc')}")
print(f" Negative: {safe_profit_calc('-100')}")Output:
🛡️ ERROR HANDLING TEST:
Good input: $7800.0
Bad input: ❌ Input Error: could not convert string to float: 'abc'
Negative: ❌ Input Error: Sales cannot be negative!🔥 Step 2: File Error Handling (Production Ready)¶
import pandas as pd
import os
def safe_read_sales(filename):
"""Production-ready file reader"""
try:
if not os.path.exists(filename):
raise FileNotFoundError(f"{filename} not found!")
df = pd.read_csv(filename)
if df.empty:
raise ValueError("File is empty!")
return df
except FileNotFoundError as e:
print(f"⚠️ {e}")
print(" 📁 Creating backup data...")
return pd.DataFrame({'Sales': [25000, 28000]}) # BACKUP!
except pd.errors.EmptyDataError:
print("⚠️ Empty file detected")
return pd.DataFrame()
except Exception as e:
print(f"💥 Critical error: {e}")
print(" 🆘 Alerting DevOps team...")
return None
## TEST FILE ERRORS
print("📁 PRODUCTION FILE HANDLING:")
df = safe_read_sales('nonexistent.csv') # Triggers backup!
print(f" ✅ Backup data loaded: {len(df)} rows")🧠 Step 3: Custom Exceptions = Enterprise Level¶
class BusinessError(Exception):
"""Custom business exceptions"""
pass
class NegativeSalesError(BusinessError):
pass
class LowProfitError(BusinessError):
pass
def enterprise_profit_calc(sales, costs):
"""Enterprise-grade calculator"""
try:
if sales < 0:
raise NegativeSalesError("Sales cannot be negative!")
profit = sales * 0.28 - costs
if profit < 1000:
raise LowProfitError(f"Profit too low: ${profit}")
return profit
except NegativeSalesError as e:
print(f"🚨 BUSINESS ALERT: {e}")
return 0
except LowProfitError as e:
print(f"⚠️ BUSINESS WARNING: {e}")
return profit # Still return for analysis
except Exception as e:
print(f"💥 SYSTEM ERROR: {e}")
raise # Re-raise for logging
## ENTERPRISE TEST
print("🏢 ENTERPRISE ERROR HANDLING:")
print(f" Normal: ${enterprise_profit_calc(35000, 12000)}")
print(f" Low: ${enterprise_profit_calc(15000, 12000)}")📊 Step 4: Finally + Context Managers¶
## CLEANUP GUARANTEED
def safe_database_operation():
file = None
try:
file = open('temp_report.csv', 'w')
file.write("Sales,Profit\n25000,5000")
print("✅ Data written!")
except Exception as e:
print(f"❌ Write failed: {e}")
finally:
if file:
file.close()
print("🔒 File closed safely!")
safe_database_operation()📋 Error Handling Hierarchy (Pro Strategy)¶
| Level | Code | When | Business Impact |
|---|---|---|---|
| Specific | except ValueError: | Known issues | Clean UX |
| Business | except NegativeSalesError: | Domain rules | Smart alerts |
| Catch-all | except Exception: | Unknown bugs | Never crash |
| Finally | finally: | Cleanup | Resource safety |
| Re-raise | raise | Critical issues | DevOps alert |
🏆 YOUR EXERCISE: Build PRODUCTION Error Handler¶
## MISSION: Enterprise-grade sales analyzer!
class SalesAnalyzerError(Exception):
pass
def production_sales_analyzer(filename):
"""FULL PRODUCTION ERROR HANDLING"""
try:
# 1. VALIDATE FILE
if not filename.endswith('.csv'):
raise SalesAnalyzerError("Must be CSV file!")
# 2. READ SAFELY
df = pd.read_csv(filename)
if df.empty:
raise SalesAnalyzerError("Empty file!")
# 3. BUSINESS VALIDATION
if (df['Sales'] < 0).any():
raise SalesAnalyzerError("Negative sales detected!")
# 4. CALCULATE
df['Profit'] = df['Sales'] * 0.28 - df['Costs']
total_profit = df['Profit'].sum()
return df, total_profit
except FileNotFoundError:
print("📁 Using backup data...")
backup_df = pd.DataFrame({'Sales': [25000], 'Costs': [18000]})
return production_sales_analyzer_backup(backup_df)
except SalesAnalyzerError as e:
print(f"🚨 BUSINESS ERROR: {e}")
return None, 0
except Exception as e:
print(f"💥 CRITICAL: {e}")
raise
finally:
print("🔒 Resources cleaned up")
def production_sales_analyzer_backup(df):
df['Profit'] = df['Sales'] * 0.28 - df['Costs']
return df, df['Profit'].sum()
## TEST PRODUCTION CODE
print("🏭 PRODUCTION TEST:")
df, profit = production_sales_analyzer('good_data.csv') # Would work
print(f" ✅ Profit: ${profit:,.0f}")YOUR MISSION:
Create sample CSV
good_data.csvTest ALL error scenarios
Screenshot → “I write production code!”
🎉 What You Mastered¶
| Skill | Status | Business Power |
|---|---|---|
| Try/Except | ✅ | Never crash |
| Specific errors | ✅ | Clean UX |
| Custom exceptions | ✅ | Enterprise |
| Finally cleanup | ✅ | Resource safe |
| Production ready | ✅ | $150K level |
Next: Libraries Overview (Pandas/NumPy = Replace Excel teams!)
print("🎊" * 25)
print("ERROR HANDLING = PRODUCTION SUPERHERO!")
print("💻 Never crash = $150K+ Senior Engineer!")
print("🚀 Netflix/Amazon LIVE by these patterns!")
print("🎊" * 25)can we appreciate how try/except turns "production outage → 150K SREs. This isn’t error handling—it’s mission-critical reliability that gets them senior offers while classmates debug panic at 3 AM!
# Your code hereExercises¶
Exercise 1¶
Write safe_divide(a, b) that returns a / b but returns None if division by zero occurs, without raising.
Exercise 2¶
Create parse_int(s) that returns an int or None on ValueError.
Exercise 3¶
Write read_key(d, key) that returns d[key] or a default message if missing, without raising KeyError.