When Things Go Wrong — Error Handling, Debugging, and Logging
Lesson opener
In one line: 1. Three types of errors and how to identify each.
Why it matters: This shows up at work when you need to 1. Three types of errors and how to identify each.
Before this lesson: Conditionals / Files & exceptions
Before you start
| Resource | Link |
|---|---|
| Previous | Functions |
| Next | OOP in Python |
| Prerequisites | Conditionals, Files & exceptions |
| Time | ~60 minutes |
| What you need | Python 3.x locally or Google Colab |
What you will learn
- Three types of errors and how to identify each
- Why debugging and logging matter more than scattered
print()calls try/exceptblocks — every keyword explained- Built-in exceptions — the ones you will encounter most at work
- Custom exceptions — write your own
- The
loggingmodule — five levels, handlers, formatters - Common exception-handling mistakes
- Why this separates hobby scripts from professional code
Section 1 — Three types of errors
Type 1: Syntax errors
Plain English: Code Python cannot even read. Caught before the program runs. The error message points to the exact line.
# Syntax error — missing colon
def calculate_tax(amount) # SyntaxError!
return amount * 0.18Expected message:
SyntaxError: expected ':'Syntax errors are like spelling mistakes — the interpreter refuses to start. Fix: read the line number in the traceback.
Type 2: Runtime errors (exceptions)
Code Python understands but fails while running. The program starts, then crashes at the failing line.
def divide(a, b):
return a / b
result = divide(10, 0)
# ZeroDivisionError: division by zeroThe car started fine. It hit something unexpected on the road.
Type 3: Logical errors
Code runs without crashing but gives the wrong answer. Only you know the result is wrong — Python does not.
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
def fahrenheit_to_celsius(f):
return (f - 32) * 5 / 9
temp_c = 25
# Intends C → F but accidentally uses F → C formula:
result = fahrenheit_to_celsius(temp_c)
print(result) # -3.89 — wrong, no error!Logical errors are the most dangerous. Only testing with known inputs finds them.
| Type | When caught | Example | Fix |
|---|---|---|---|
| Syntax | Before running | Missing : or ) | Read error line |
| Runtime | While running | Divide by zero | try/except or validate input |
| Logical | Never (by Python) | Wrong formula | Tests + debugging |
Section 2 — The try/except block — every keyword
try:
# Code that might fail
result = int(input("Enter a number: "))
print(f"Result: {100 / result}")
except ValueError:
# Runs if int() conversion fails
print("That was not a number.")
except ZeroDivisionError:
# Runs if user entered 0
print("Cannot divide by zero.")
except Exception as e:
# Catches ANY other exception; e holds details
print(f"Unexpected error: {e}")
else:
# Runs ONLY if NO exception occurred in try
print("Calculation successful!")
finally:
# ALWAYS runs — exception or not
print("Calculation attempt complete.")| Keyword | Plain English |
|---|---|
try | "Attempt this block — it might fail." |
except SomeError | "If this specific error happens, run this instead of crashing." |
except Exception as e | Catch-all for unexpected errors; log e, do not hide bugs silently. |
else | "Only if try succeeded completely." The else block is skipped if any except ran. |
finally | "Always run — close files, release connections." Runs even if you return inside try or except. |
Order matters: Put specific exceptions before broad Exception.
Real workplace example — file processing
def read_sales_data(filename):
file = None
try:
file = open(filename, 'r')
data = file.read()
return data
except FileNotFoundError:
print(f"File not found: {filename}")
return None
except PermissionError:
print(f"No permission to read: {filename}")
return None
finally:
# Always close the file — even if error occurred
if file:
file.close()
# Better: use context manager (with statement)
def read_sales_data_better(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
print(f"File not found: {filename}")
return NonePlain English: finally guarantees cleanup. The with statement is preferred in modern Python — it closes the file automatically.
Section 3 — Built-in exceptions you will actually encounter
# ValueError — right type, wrong value
int("hello") # ValueError
int("3.14") # ValueError
# TypeError — wrong type entirely
"hello" + 5 # TypeError
len(42) # TypeError
# ZeroDivisionError — divide by zero
10 / 0 # ZeroDivisionError
# IndexError — list index out of range
items = [1, 2, 3]
items[5] # IndexError
# KeyError — dictionary key not found
person = {"name": "Priya"}
person["age"] # KeyError
# AttributeError — object has no attribute
"hello".push("!") # AttributeError (strings have no .push())
# FileNotFoundError — file does not exist
open("missing.csv") # FileNotFoundError
# ImportError — module not found
import numpy # ImportError if not installed
# NameError — variable not defined
print(undefined_var) # NameError
# RecursionError — infinite recursion
def f(): f()
f() # RecursionErrorException hierarchy
Plain English: Exception is the parent of almost all errors you will handle. Catching Exception catches everything below it. Catching ValueError catches only that type — prefer specific handlers when you know what can fail.
Section 4 — Custom exceptions
Plain English: Built-in exceptions are generic. ValueError tells you a value was wrong but not which value or why. Custom exceptions carry meaning for your application's domain.
class InsufficientFundsError(Exception):
"""Raised when account balance is too low."""
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(
f"Cannot withdraw ₹{amount:,}. "
f"Available balance: ₹{balance:,}"
)
class InvalidSalaryError(ValueError):
"""Raised when salary is outside valid range."""
pass
class ProductNotFoundError(Exception):
"""Raised when product ID doesn't exist in catalogue."""
def __init__(self, product_id):
self.product_id = product_id
super().__init__(f"Product ID '{product_id}' not found")
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(self.balance, amount)
self.balance -= amount
return self.balance
account = BankAccount(10000)
try:
account.withdraw(15000)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")
print(f"You tried to withdraw: ₹{e.amount:,}")
print(f"Your balance was: ₹{e.balance:,}")Output:
Transaction failed: Cannot withdraw ₹15,000. Available balance: ₹10,000
You tried to withdraw: ₹15,000
Your balance was: ₹10,000When to raise
def set_salary(amount):
if not isinstance(amount, (int, float)):
raise TypeError(
f"Salary must be a number, got {type(amount).__name__}"
)
if amount < 0:
raise ValueError(f"Salary cannot be negative: {amount}")
if amount > 10_000_000:
raise InvalidSalaryError(f"Salary ₹{amount:,} exceeds maximum")
return amountraise is how you generate an exception when your code detects an invalid state the caller must know about.
Section 5 — The logging module
Plain English: print() is for development. logging is for production.
print() problem | logging solution |
|---|---|
| Disappears when terminal closes | Writes to files with timestamps |
| No severity levels | DEBUG through CRITICAL hierarchy |
| Screen only | Handlers for file + console |
The five log levels
| Level | When to use | Method |
|---|---|---|
| DEBUG | Detailed diagnostic info | logging.debug() |
| INFO | Confirmation things work | logging.info() |
| WARNING | Unexpected but app still works | logging.warning() |
| ERROR | Something failed | logging.error() |
| CRITICAL | Serious failure, may stop app | logging.critical() |
Levels are a hierarchy: DEBUG < INFO < WARNING < ERROR < CRITICAL. Setting level=logging.WARNING hides DEBUG and INFO.
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.debug("Starting data processing")
logging.info("Loaded 1,247 rows from CSV")
logging.warning("Column 'email' has 23 missing values")
logging.error("Could not connect to database")
logging.critical("Disk space below 5% — halting")Logging to file and console
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('app.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
def process_orders(orders):
logger.info(f"Processing {len(orders)} orders")
success = failed = 0
for order in orders:
try:
logger.debug(f"Processing order {order['id']}")
success += 1
except Exception as e:
logger.error(f"Failed order {order['id']}: {e}")
failed += 1
logger.info(f"Complete. Success: {success}, Failed: {failed}")logging.error() vs logging.exception()
import logging
logging.basicConfig(level=logging.DEBUG)
try:
result = 10 / 0
except ZeroDivisionError:
logging.error("Division failed")
# Output: ERROR - Division failed (no traceback)
logging.exception("Division failed")
# Output: ERROR - Division failed
# PLUS full traceback with line numbersAlways use logging.exception() inside except blocks — it includes the traceback automatically.
Section 6 — Debugging techniques
Technique 1: Read the traceback (bottom-up)
Traceback (most recent call last):
File "sales.py", line 42, in process_sales
total = calculate_total(orders)
File "sales.py", line 15, in calculate_total
return sum(order['amount'] for order in orders)
KeyError: 'amount'- Start from the bottom — that is the actual error
- The line above is where it occurred
- Lines above that show the call chain
The traceback is not an enemy. It is a map.
Technique 2: Strategic logging
def calculate_bonus(employees):
logger.debug(f"Input: {len(employees)} employees")
total = 0
for emp in employees:
logger.debug(
f"Processing: {emp['name']}, "
f"salary: {emp.get('salary', 'MISSING')}"
)
bonus = emp['salary'] * 0.10
total += bonus
logger.info(f"Total bonuses: ₹{total:,}")
return totalTechnique 3: assert statements (development)
def calculate_tax(amount, rate):
assert isinstance(amount, (int, float)), \
f"amount must be numeric, got {type(amount)}"
assert 0 <= rate <= 1, \
f"rate must be between 0 and 1, got {rate}"
return amount * rateUse during development — not as production error handling.
Technique 4: pdb — Python debugger
import pdb
def buggy_function(data):
result = []
for item in data:
pdb.set_trace() # pause — n=next, p var=print, c=continue, q=quit
result.append(item * 2)
return resultSection 7 — Common mistakes
Mistake 1 — Catching too broadly
# WRONG — catches KeyboardInterrupt too:
try:
risky_operation()
except:
pass
# RIGHT:
try:
risky_operation()
except ValueError as e:
logger.error(f"Invalid value: {e}")
except FileNotFoundError as e:
logger.error(f"File missing: {e}")Mistake 2 — Empty except blocks
# WRONG:
try:
connect_to_database()
except:
pass
# RIGHT:
try:
connect_to_database()
except Exception as e:
logger.exception("Database connection failed")
raiseMistake 3 — Exceptions for flow control
# WRONG:
def get_user(users, user_id):
try:
return users[user_id]
except KeyError:
return None
# RIGHT:
return users.get(user_id)Mistake 4 — Logging without handling
Log and decide: recover, skip, or re-raise.
Mistake 5 — Not enough context
# WRONG:
logging.error(f"Order failed: {e}")
# RIGHT:
logging.error(
f"Order failed. ID: {order_id}, Customer: {customer_id}, "
f"Amount: ₹{amount:,}, Error: {e}",
exc_info=True
)Section 8 — Complete practical example
import logging
from datetime import datetime
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(funcName)s - %(message)s',
handlers=[
logging.FileHandler(f'sales_{datetime.now().strftime("%Y%m%d")}.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class InvalidOrderError(ValueError):
def __init__(self, order_id, reason):
self.order_id = order_id
self.reason = reason
super().__init__(f"Order {order_id} invalid: {reason}")
class PaymentFailedError(Exception):
def __init__(self, order_id, amount):
self.order_id = order_id
self.amount = amount
super().__init__(
f"Payment of ₹{amount:,} failed for order {order_id}"
)
def validate_order(order):
if not order.get('id'):
raise InvalidOrderError('UNKNOWN', 'Missing order ID')
if not order.get('amount') or order['amount'] <= 0:
raise InvalidOrderError(order['id'], 'Invalid amount')
if not order.get('customer_id'):
raise InvalidOrderError(order['id'], 'Missing customer ID')
def process_payment(order_id, amount):
if amount > 500000:
raise PaymentFailedError(order_id, amount)
return True
def process_order(order):
order_id = order.get('id', 'UNKNOWN')
try:
logger.info(f"Processing order {order_id}")
validate_order(order)
process_payment(order_id, order['amount'])
logger.info(f"Order {order_id} complete. Amount: ₹{order['amount']:,}")
return {'status': 'success', 'id': order_id}
except InvalidOrderError as e:
logger.warning(f"Invalid order: {e}")
return {'status': 'invalid', 'error': str(e)}
except PaymentFailedError as e:
logger.error(f"Payment failed for order {order_id}: {e}")
return {'status': 'payment_failed', 'error': str(e)}
except Exception:
logger.exception(f"Unexpected error processing order {order_id}")
return {'status': 'error', 'error': 'unexpected'}
orders = [
{'id': 'ORD001', 'amount': 45000, 'customer_id': 'C01'},
{'id': 'ORD002', 'amount': -100, 'customer_id': 'C02'},
{'id': 'ORD003', 'amount': 750000, 'customer_id': 'C03'},
{'id': None, 'amount': 1000, 'customer_id': 'C04'},
]
for order in orders:
print(f"Result: {process_order(order)}")Practice
Exercise 1 — Identify error types
For each snippet, label: syntax, runtime, or logical. Check answers after attempting.
def f(x) return x10 / 0celsius_to_fahrenheit(25)called with wrong formula — runs, wrong output
Exercise 2 — Add exception handling
Take a CSV-reading function with no error handling. Add try/except, logging, and user-friendly messages.
Exercise 3 — Custom exceptions
Build a simple inventory with InsufficientStockError and InvalidQuantityError. Raise and handle with logging.
Exercise 4 — Debug the code
Fix three buggy functions — one syntax, one runtime, one logical — each with a test showing wrong output.
Checklist
- [ ] I can name the three types of errors with an example of each
- [ ] I can write
try/except/else/finallyfrom memory - [ ] I know the difference between
except ValueErrorandexcept Exception - [ ] I can create a custom exception that carries extra information
- [ ] I can set up logging with file and console output
- [ ] I know when to use
logging.exception()vslogging.error() - [ ] I can explain why bare
except:is bad - [ ] I can read a traceback and identify where the error occurred
Interview Prep — Skill Mastery Challenge
Syntax errors are caught before the program runs — Python cannot parse the code. Exceptions occur at runtime — the code is valid Python but something fails during execution.
The finally block always executes regardless of whether an exception occurred. Used for cleanup — closing files, database connections, releasing resources.
Both log at ERROR level. logging.exception() additionally captures and logs the full traceback. Always use logging.exception() inside except blocks.
When a built-in exception does not carry enough context for your domain — e.g. distinguishing order-not-found from file-not-found, or attaching order ID and amount to the error.
It silently swallows every error including KeyboardInterrupt. Always catch specific exceptions and at minimum log them.
What's next
OOP in Python — classes, raise inside methods, and encapsulation that validates before changing state.