Exception Handling Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Test your mastery of exception handling by building real-world resilient data ingestion pipelines.
Resilient CSV parser with error recovery
When parsing batches of records, a single corrupt line should not crash the entire ingestion pipeline.
records = ["101,Aarav,95", "102,BadScore,N/A", "103,Tara,88"]valid_students = []
for line in records: try: sid, name, score_str = line.split(",") score = int(score_str) valid_students.append((name, score)) except (ValueError, IndexError) as err: print(f"Skipping corrupt line '{line}': {err}")
print(f"Ingested {len(valid_students)} students")Example 1 · Dividing text values safely
def safe_divide(a_str, b_str): try: a = float(a_str) b = float(b_str) return round(a / b, 2) except ValueError: return "Invalid input: numbers required" except ZeroDivisionError: return "Math error: division by zero"
print(safe_divide("10", "2"))print(safe_divide("10", "0"))print(safe_divide("10", "x"))5.0 Math error: division by zero Invalid input: numbers required
What this code does
- Parses input strings to floats.
- Catches ValueError and ZeroDivisionError distinctly.
- Outputs valid quotient (5.0) and helpful error messages.
The parser safely skips record 102 and successfully ingests Aarav and Tara.
Retry loop pattern
Wrap flaky operations in a while loop that attempts execution up to a maximum retry limit.
attempts = 0max_attempts = 3success = False
while attempts < max_attempts and not success: try: attempts += 1 # Simulated operation that succeeds on attempt 2 if attempts < 2: raise ConnectionError("Server busy") success = True print(f"Connected on attempt {attempts}") except ConnectionError: if attempts == max_attempts: print("All retries failed")Example 2 · Retry until the input is valid
inputs = ["abc", "-4", "25"]attempts = 0
for text in inputs: attempts += 1 try: qty = int(text) if qty <= 0: raise ValueError("Quantity must be positive") except ValueError as err: print(f"Attempt {attempts} failed: {err}") else: print(f"Accepted {qty} after {attempts} attempts") breakAttempt 1 failed: invalid literal for int() with base 10: 'abc' Attempt 2 failed: Quantity must be positive Accepted 25 after 3 attempts
What this code does
- Each pass tries one input. Both bad text and a non-positive number raise
ValueError. elseruns only for a good input, andbreakstops the retries.
The retry loop cleanly handles transient connection errors.
Finish up
Mark complete & continue
Next: Must-do problems: Exception Handling