An exception stops the program
quantity = int("two")ValueError: invalid literal for int() with base 10: 'two'try / except: handle it
def parse_quantity(raw: str) -> int | None:
try:
return int(raw)
except ValueError:
print(f" bad quantity {raw!r}, skipping")
return None
print(parse_quantity("3"))
print(parse_quantity("two"))3 bad quantity 'two', skipping None
def load_file(path):
try:
f = open(path, encoding="utf-8")
except FileNotFoundError as e:
print("missing:", e.filename)
else:
print("first line:", f.readline().strip()) # runs only if no exception
f.close()
finally:
print("done checking", path) # always runs
load_file("data/orders.csv")
load_file("data/payments.csv")first line: order_id,customer_id,product,quantity,price,status,order_date done checking data/orders.csv missing: data/payments.csv done checking data/payments.csv
| Block | Runs when |
|---|---|
| try | Always first: the risky code |
| except SomeError | That error happened inside try |
| else | No error happened |
| finally | Always, error or not (cleanup) |
Validate rows, keep the rejects
๐Raw row
๐Validate
Required fields, numbers, duplicates
โ Valid โ load
๐๏ธRejected โ quarantine
With a reason, for someone to fix
import csv
def validate(row: dict) -> list[str]:
"""Return a list of problems with this row (empty list = valid)."""
problems = []
if not row["customer_id"].strip():
problems.append("missing customer_id")
try:
if int(row["quantity"]) <= 0:
problems.append("quantity must be > 0")
except ValueError:
problems.append(f"quantity not a number: {row['quantity']!r}")
return problems
valid, rejected, seen = [], [], set()
with open("data/orders.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
problems = validate(row)
if row["order_id"] in seen:
problems.append("duplicate order_id")
seen.add(row["order_id"])
if problems:
rejected.append({**row, "reason": "; ".join(problems)})
else:
valid.append(row)
print(f"valid: {len(valid)}, rejected: {len(rejected)}")
for r in rejected:
print(f" order {r['order_id']}: {r['reason']}")valid: 7, rejected: 3 order 107: duplicate order_id order 108: missing customer_id order 109: quantity not a number: 'two'
Custom exceptions: stop a broken batch
class DataQualityError(Exception):
"""Raised when a batch is too broken to load."""
def check_batch(valid: list, rejected: list, max_bad_ratio: float = 0.2) -> None:
ratio = len(rejected) / (len(valid) + len(rejected))
if ratio > max_bad_ratio:
raise DataQualityError(f"{ratio:.0%} of rows rejected (limit {max_bad_ratio:.0%})")
print(f"batch OK: {ratio:.0%} rejected")
check_batch(valid, rejected, max_bad_ratio=0.5)batch OK: 30% rejected
check_batch(valid, rejected, max_bad_ratio=0.2)DataQualityError: 30% of rows rejected (limit 20%)A named exception like DataQualityError tells whoever reads the alert exactly what kind of problem it is.
Logging
import logging, sys
logging.basicConfig(
level=logging.INFO,
format="%(levelname)-7s %(name)s: %(message)s", # add %(asctime)s in real jobs
stream=sys.stdout,
force=True,
)
log = logging.getLogger("shopkart.orders")
log.debug("not shown: level is INFO")
log.info("loaded %d valid rows", len(valid))
log.warning("%d rows rejected", len(rejected))
try:
1 / 0
except ZeroDivisionError:
log.exception("this logs the full traceback too")INFO shopkart.orders: loaded 7 valid rows WARNING shopkart.orders: 3 rows rejected ERROR shopkart.orders: this logs the full traceback too Traceback (most recent call last): File "logging", line 15, in <module> ZeroDivisionError: division by zero
| Level | Use for |
|---|---|
| DEBUG | Details for developers (off in production) |
| INFO | Normal progress: 'loaded 7 rows' |
| WARNING | Something odd but the job continues: 3 rows rejected |
| ERROR | A step failed |
| CRITICAL | The whole job can't continue |
Use log.info("loaded %d rows", n) style arguments rather than f-strings: the text is only built if the level is enabled. log.exception() inside an except block also records the traceback.
Retries with exponential backoff
import time
calls = {"n": 0}
def flaky_fetch():
"""Pretend network call: fails twice, then works."""
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("network blip")
return {"rows": 42}
def with_retries(fn, attempts=4, base_delay=0.01):
for attempt in range(1, attempts + 1):
try:
return fn()
except ConnectionError as e:
if attempt == attempts:
raise
delay = base_delay * 2 ** (attempt - 1) # exponential backoff: 1x, 2x, 4x...
print(f"attempt {attempt} failed ({e}); retrying in {delay:.2f}s")
time.sleep(delay)
print(with_retries(flaky_fetch))attempt 1 failed (network blip); retrying in 0.01s
attempt 2 failed (network blip); retrying in 0.02s
{'rows': 42}๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Difference between an error and an exception in Python?Fresher+
Q2How do you design error handling for a data pipeline?1โ3 yrs+
Q3What is the purpose of finally?1โ3 yrs+
Q4How do you create a custom exception?1โ3 yrs+
Q5How would you configure logging for a production pipeline?3+ yrs+
Key takeaways
- โBad data is normal: validate, quarantine, and count it.
- โFail loudly when a batch is too broken to trust.
- โLogging tells you what happened when you weren't watching.
- โNext: pulling data from APIs, where retries really matter.
Frequently asked questions
What is an exception?
An error raised while the program runs, like ValueError when converting 'two' to int. If nothing catches it, the program stops and prints a traceback.
Should I catch every exception with 'except Exception'?
Rarely. Catch the specific errors you expect and know how to handle (ValueError for bad data, ConnectionError for network blips). Catching everything hides real bugs.
Why use logging instead of print?
Logging adds levels (DEBUG to CRITICAL), timestamps and logger names, can be switched on or off per module, and can be sent to files or monitoring systems. print is for quick scripts only.
What is exponential backoff?
Waiting longer after each failed retry (1s, 2s, 4s, 8s...). It gives a struggling service time to recover instead of hammering it.
What should happen to bad rows in a pipeline?
Keep them, with a reason, in a rejected/quarantine file or table, count them, and stop the load if too many are bad. Never drop data silently.
๐ง Quick check: errors and logging
1. The 'else' block of try/except runs when...
2. Which logging level is for normal progress messages?
3. Retries only make sense for...
4. 30% of rows are bad and your limit is 20%. The pipeline should...
Checking your accessโฆ