Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 06 / Stage 1

Errors and exceptions

Goal: Read error messages calmly and handle bad input without your program crashing. Time: ~1 hour

What you will learn

  • Syntax errors vs exceptions
  • How to read a traceback
  • Common built-in exceptions
  • try / except (specific exceptions, many excepts, as e)
  • else and finally
  • raise, re-raise, and raise ... from
  • Custom exceptions
  • EAFP vs LBYL
  • Good habits for handling errors

Topics in this part

Practice

Python workbench — write and run code here

Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.

Write each answer as a function. Call it at the bottom with the sample values so the file runs on its own (no input() needed).


Exercise 1: Safe divide

Scenario: A trip app splits fuel cost between friends. Someone may type 0 friends. What to do: Write safe_divide(total, people) that returns total / people, or the text "Cannot split between 0 people" on ZeroDivisionError. Print safe_divide(1500, 3) and safe_divide(1500, 0).

Sample output:

500.0
Cannot split between 0 people

💡 Hint: try: return total / people then except ZeroDivisionError:.


Show the solution to Exercise 1
"""Exercise 1: Safe divide (catching ZeroDivisionError).

Run: python ex01.py   (macOS/Linux: python3 ex01.py)
"""


def safe_divide(total: float, people: int) -> float | str:
    try:
        return total / people
    except ZeroDivisionError:
        return "Cannot split between 0 people"


print(safe_divide(1500, 3))
print(safe_divide(1500, 0))

Exercise 2: Number or default

Scenario: A form field for "number of tickets" may contain junk. What to do: Write to_int(text, default=0) that converts text to int, or returns default if it fails. Print to_int("4"), to_int("four") and to_int("", 1).

Sample output:

4
0
1

💡 Hint: int() raises ValueError for bad text.


Show the solution to Exercise 2
"""Exercise 2: Number or default (catching ValueError).

Run: python ex02.py   (macOS/Linux: python3 ex02.py)
"""


def to_int(text: str, default: int = 0) -> int:
    try:
        return int(text)
    except ValueError:
        return default


print(to_int("4"))
print(to_int("four"))
print(to_int("", 1))

Exercise 3: Menu price lookup

Scenario: A canteen app looks up prices. Unknown items should not crash it. What to do: Write get_price(menu, item) using EAFP (try / except KeyError) that returns the price or "<item> not on menu". Then write get_price_lbyl(menu, item) that does the same with LBYL (if item in menu). Print both functions for "tea" and "pizza".

Starting data:

menu = {"tea": 15, "vada pav": 25}

Sample output:

15
pizza not on menu
15
pizza not on menu

💡 Hint: Both versions should give the same answers.


Show the solution to Exercise 3
"""Exercise 3: Menu price lookup, EAFP and LBYL.

Run: python ex03.py   (macOS/Linux: python3 ex03.py)
"""


def get_price(menu: dict, item: str) -> int | str:
    """EAFP: try it, handle the KeyError."""
    try:
        return menu[item]
    except KeyError:
        return f"{item} not on menu"


def get_price_lbyl(menu: dict, item: str) -> int | str:
    """LBYL: check first."""
    if item in menu:
        return menu[item]
    return f"{item} not on menu"


menu = {"tea": 15, "vada pav": 25}
print(get_price(menu, "tea"))
print(get_price(menu, "pizza"))
print(get_price_lbyl(menu, "tea"))       # same answers with LBYL
print(get_price_lbyl(menu, "pizza"))

Exercise 4: Order total with many errors

Scenario: An order is a list of (item, qty_text) pairs. Items may be missing from the price list, and quantities may be bad text. What to do: Write order_total(prices, order) that adds up the valid lines, prints a warning for each bad line, and returns the total. Handle KeyError and ValueError in separate except blocks. Use else to add the line to the total. Then print the total as Total: ₹120.

Starting data:

prices = {"pen": 10, "notebook": 45}
order = [("pen", "3"), ("eraser", "2"), ("notebook", "two"), ("notebook", "2")]

Sample output:

Skipping 'eraser': not in price list
Skipping 'notebook': quantity 'two' is not a number
Total: ₹120

💡 Hint: Put both risky lines in a small try: price = prices[item] and qty = int(qty_text).


Show the solution to Exercise 4
"""Exercise 4: Order total with separate except blocks and else.

Run: python ex04.py   (macOS/Linux: python3 ex04.py)
"""


def order_total(prices: dict, order: list[tuple[str, str]]) -> int:
    total = 0
    for item, qty_text in order:
        try:
            price = prices[item]
            qty = int(qty_text)
        except KeyError:
            print(f"Skipping '{item}': not in price list")
        except ValueError:
            print(f"Skipping '{item}': quantity '{qty_text}' is not a number")
        else:
            total += price * qty          # only runs when both lines worked
    return total


prices = {"pen": 10, "notebook": 45}
order = [("pen", "3"), ("eraser", "2"), ("notebook", "two"), ("notebook", "2")]
print(f"Total: ₹{order_total(prices, order):,}")

Exercise 5: Validate age

Scenario: A gym sign-up form needs an age between 16 and 80. What to do: Write validate_age(text) that:

  • raises ValueError("Age must be a whole number") if the text is not a number (use raise ... from),
  • raises ValueError("Age must be between 16 and 80") if out of range,
  • returns the age as int otherwise.

Test it with the simulated inputs below. Print each input with repr() style quotes ({typed!r:<5}), then the result.

Starting data:

inputs = ["25", "abc", "12", "81"]

Sample output:

'25'  -> OK 25
'abc' -> Error: Age must be a whole number
'12'  -> Error: Age must be between 16 and 80
'81'  -> Error: Age must be between 16 and 80

💡 Hint: Convert inside try; check the range after the try. {typed!r} shows the text with its quotes.


Show the solution to Exercise 5
"""Exercise 5: Validate age (raise and raise ... from).

Run: python ex05.py   (macOS/Linux: python3 ex05.py)
"""


def validate_age(text: str) -> int:
    try:
        age = int(text)
    except ValueError as e:
        raise ValueError("Age must be a whole number") from e
    if not 16 <= age <= 80:
        raise ValueError("Age must be between 16 and 80")
    return age


inputs = ["25", "abc", "12", "81"]

for typed in inputs:
    try:
        print(f"{typed!r:<5} -> OK {validate_age(typed)}")
    except ValueError as e:
        print(f"{typed!r:<5} -> Error: {e}")

Exercise 6: Out of stock (custom exception)

Scenario: A grocery app must stop orders that need more stock than is left. What to do:

  1. Create class OutOfStockError(Exception) (use the two-line pattern from README section 7).
  2. Write buy(stock, item, qty) that raises OutOfStockError with a message like "Only 2 left of milk" when qty is more than the stock, and otherwise reduces the stock.
  3. Process the purchases below and print the result of each (the label buy milk x3 padded to 13 characters).

Starting data:

stock = {"milk": 5, "bread": 2}
purchases = [("milk", 3), ("bread", 4), ("milk", 2)]

Sample output:

buy milk x3   -> OK, milk left: 2
buy bread x4  -> Sorry: Only 2 left of bread
buy milk x2   -> OK, milk left: 0

💡 Hint: raise OutOfStockError(f"Only {stock[item]} left of {item}").


Show the solution to Exercise 6
"""Exercise 6: Out of stock (custom exception).

Run: python ex06.py   (macOS/Linux: python3 ex06.py)
"""


class OutOfStockError(Exception):
    """Raised when an order needs more stock than is left."""


def buy(stock: dict, item: str, qty: int) -> None:
    if qty > stock[item]:
        raise OutOfStockError(f"Only {stock[item]} left of {item}")
    stock[item] -= qty


stock = {"milk": 5, "bread": 2}
purchases = [("milk", 3), ("bread", 4), ("milk", 2)]

for item, qty in purchases:
    label = f"buy {item} x{qty}"
    try:
        buy(stock, item, qty)
    except OutOfStockError as e:
        print(f"{label:<13} -> Sorry: {e}")
    else:
        print(f"{label:<13} -> OK, {item} left: {stock[item]}")

Exercise 7: Mini ATM session

Scenario: An ATM processes a list of commands typed by a user (simulated). What to do: Commands look like "deposit 500", "withdraw 200", "balance". Starting balance is ₹1,000.

  • Create InsufficientBalanceError(Exception).
  • Bad commands (unknown word, missing amount, amount not a number, amount ≤ 0) must print a clear message, not crash.
  • Use finally to count how many commands were processed.
  • Print each command padded to 13 characters, then -> and the result. Show money as ₹1,000.

Starting data:

commands = ["balance", "withdraw 300", "withdraw 5000", "deposit abc",
            "deposit 250", "deposit -5", "fly 10", "withdraw", "balance"]

Sample output:

balance       -> Balance: ₹1,000
withdraw 300  -> Withdrew ₹300
withdraw 5000 -> Error: balance ₹700 is less than ₹5,000
deposit abc   -> Error: amount 'abc' is not a number
deposit 250   -> Deposited ₹250
deposit -5    -> Error: amount must be more than 0
fly 10        -> Error: unknown command 'fly'
withdraw      -> Error: please give an amount
balance       -> Balance: ₹950
Processed 9 commands

💡 Hint: parts = command.split(). Write a helper that reads the amount: if len(parts) < 2, raise ValueError("please give an amount"); if int() fails, raise a clearer ValueError. Then one except (ValueError, InsufficientBalanceError) as e: prints every error the same way.

Show the solution to Exercise 7
"""Exercise 7: Mini ATM session (custom exception, many excepts, finally).

Run: python ex07.py   (macOS/Linux: python3 ex07.py)
"""


class InsufficientBalanceError(Exception):
    """Raised when a withdrawal is more than the balance."""


def parse_amount(parts: list[str]) -> int:
    """Read the amount from ['withdraw', '300']. Raises ValueError if it is bad."""
    if len(parts) < 2:                               # e.g. just "withdraw"
        raise ValueError("please give an amount")
    text = parts[1]
    try:
        amount = int(text)
    except ValueError:
        raise ValueError(f"amount '{text}' is not a number") from None
    if amount <= 0:
        raise ValueError("amount must be more than 0")
    return amount


def run_command(balance: int, command: str) -> tuple[int, str]:
    """Return (new balance, message). May raise an exception."""
    parts = command.split()
    action = parts[0] if parts else ""
    if action == "balance":
        return balance, f"Balance: ₹{balance:,}"
    if action == "deposit":
        amount = parse_amount(parts)
        return balance + amount, f"Deposited ₹{amount:,}"
    if action == "withdraw":
        amount = parse_amount(parts)
        if amount > balance:
            raise InsufficientBalanceError(
                f"balance ₹{balance:,} is less than ₹{amount:,}"
            )
        return balance - amount, f"Withdrew ₹{amount:,}"
    raise ValueError(f"unknown command '{action}'")


def atm_session(commands: list[str], balance: int = 1000) -> int:
    processed = 0
    for command in commands:
        try:
            balance, message = run_command(balance, command)
        except (ValueError, InsufficientBalanceError) as e:
            message = f"Error: {e}"
        finally:
            processed += 1                           # counted, error or not
        print(f"{command:<13} -> {message}")
    print(f"Processed {processed} commands")
    return balance


commands = ["balance", "withdraw 300", "withdraw 5000", "deposit abc",
            "deposit 250", "deposit -5", "fly 10", "withdraw", "balance"]
atm_session(commands)

Common mistakes

Mistake Why it is wrong Fix
Bare except: Hides every error, even typos and Ctrl+C except ValueError: (be specific)
except Exception: pass The error disappears silently Print/log it, or let it crash
A huge try block You do not know which line failed Wrap only the risky line
Reading the traceback from the top The real cause is at the bottom Read the last line first
raise ValueError with no message The user cannot tell what went wrong raise ValueError("Age must be 0-120")
Putting the "success" code in try Its errors get caught by mistake Move it to else
Using try to catch a SyntaxError in the same file The file never runs Fix the code

Quick recap

  • Syntax errors stop the file from running; exceptions happen while it runs.
  • Read a traceback bottom-up: type and message first, then the failing line.
  • try / except SpecificError as e handles a problem; many excepts are allowed.
  • else runs on success; finally always runs.
  • raise signals your own rule is broken; bare raise re-raises; raise ... from adds a cause.
  • Custom exceptions: class MyError(Exception): pass (classes come properly in Stage 2, Part 9).
  • Python prefers EAFP (try it, catch the error) over LBYL (check first).

Checklist

  • I can tell a syntax error from an exception.
  • I can read a traceback and find the failing line.
  • I know when ValueError, TypeError, KeyError and IndexError happen.
  • I can write try / except / else / finally.
  • I can raise an error with a clear message.
  • I can create and catch a custom exception.
  • I can explain EAFP vs LBYL with an example.
  • I never write a bare except:.

Search the guide