{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f39d9d77-c336-42ad-a1a3-a4c28be72888",
   "metadata": {},
   "source": [
    "# Exceptions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5b0b7545",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.075880Z",
     "iopub.status.busy": "2026-09-25T18:45:29.075308Z",
     "iopub.status.idle": "2026-09-25T18:45:29.398301Z",
     "shell.execute_reply": "2026-09-25T18:45:29.396987Z"
    },
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent  # ← Add project root, not chapters\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "from shared import thinkpython, diagram, jupyturtle\n",
    "from shared.download import download\n",
    "\n",
    "# Register as top-level modules so direct imports work in subsequent cells\n",
    "sys.modules['thinkpython'] = thinkpython\n",
    "sys.modules['diagram'] = diagram\n",
    "sys.modules['jupyturtle'] = jupyturtle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb77b8fb",
   "metadata": {},
   "source": [
    "**Learning goals:** By the end of this section you will be able to:\n",
    "\n",
    "- Distinguish between syntax errors, runtime errors (exceptions), and logic (semantic) errors\n",
    "- Read and interpret Python tracebacks to locate the source of a bug\n",
    "- Handle exceptions gracefully with `try`, `except`, `else`, and `finally`\n",
    "- Catch specific exception types and provide a meaningful response to each\n",
    "- Raise exceptions with `raise` and define custom exception classes\n",
    "- Apply print-statement debugging, `assert`, and bisection to isolate bugs systematically\n",
    "- Use the `logging` module to record diagnostic messages at appropriate severity levels"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "747e0f00",
   "metadata": {},
   "source": [
    "## Types of Errors\n",
    "\n",
    "When you write programs, things will go wrong. Before you can handle errors gracefully or fix them, you need to know what kinds of errors exist. Python programs fail in three different ways:\n",
    "\n",
    "| Error Type | When It Occurs | Example |\n",
    "|------------|----------------|---------|\n",
    "| **Syntax Error** | Code violates Python grammar; the program never starts | Missing colon, unmatched quotes |\n",
    "| **Runtime Error (Exception)** | Something goes wrong while the program is running | Division by zero, file not found |\n",
    "| **Logic (Semantic) Error** | Code runs but produces the wrong result | Incorrect algorithm, wrong formula |\n",
    "\n",
    "Python reports syntax errors before any code runs, and it cannot help you with logic errors at all, since the program does exactly what you wrote. Runtime errors are different: when one occurs, Python **raises an exception**. If nothing handles the exception, the program stops and prints an error report called a **traceback**.\n",
    "\n",
    "**Common Exception Types**\n",
    "\n",
    "Python has many built-in exception types. Here are the ones you will see most often:\n",
    "\n",
    "| Exception | Description | Example |\n",
    "|-----------|-------------|---------|\n",
    "| `ValueError` | Invalid value for operation | `int(\"hello\")` |\n",
    "| `TypeError` | Wrong type for operation | `\"5\" + 5` |\n",
    "| `ZeroDivisionError` | Division by zero | `10 / 0` |\n",
    "| `IndexError` | Index out of range | `[1, 2][5]` |\n",
    "| `KeyError` | Dictionary key not found | `{}[\"missing\"]` |\n",
    "| `FileNotFoundError` | File doesn't exist | `open(\"nonexistent.txt\")` |\n",
    "| `AttributeError` | Attribute doesn't exist | `\"text\".nonexistent()` |\n",
    "| `NameError` | Variable not defined | `print(undefined_var)` |\n",
    "\n",
    "The rest of this section follows the life of an exception: first you learn to read the traceback it produces, then to handle it, then to raise your own, and finally to track down the bugs behind it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-747e0f00",
   "metadata": {},
   "source": [
    "```{index} syntax error, runtime error, logic error\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9768ce35",
   "metadata": {},
   "source": [
    "## Reading Tracebacks\n",
    "\n",
    "When Python encounters a runtime error that nothing handles, it displays a **traceback**: an error report that shows where the error occurred. Learning to read tracebacks is essential for debugging.\n",
    "\n",
    "A traceback shows:\n",
    "\n",
    "1. **Where** the error occurred\n",
    "2. Which **lines** were executed leading to the error\n",
    "3. What **type of error** happened\n",
    "\n",
    "The order of functions in the traceback matches the order of function calls, so the most useful information is at the end. Read it from **bottom to top**:\n",
    "\n",
    "- **Bottom**: The error type and message (e.g., \"NameError: name 'cat' is not defined\")\n",
    "- **Just above it**: The line where the error actually happened\n",
    "- **Top**: The chain of function calls that led there\n",
    "\n",
    "The two functions below contain a deliberate bug."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-9768ce35",
   "metadata": {},
   "source": [
    "```{index} traceback\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a1635bcf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.400426Z",
     "iopub.status.busy": "2026-09-25T18:45:29.399531Z",
     "iopub.status.idle": "2026-09-25T18:45:29.403884Z",
     "shell.execute_reply": "2026-09-25T18:45:29.402965Z"
    }
   },
   "outputs": [],
   "source": [
    "def print_twice(value):\n",
    "    \"\"\"Print a value twice. Contains a deliberate bug for demonstration.\"\"\"\n",
    "    print(value)\n",
    "    print(cat)          # Bug: 'cat' is not defined\n",
    "\n",
    "def cat_twice():\n",
    "    \"\"\"Function that calls print_twice.\"\"\"\n",
    "    line1 = \"Bing tiddle \"\n",
    "    line2 = \"tiddle bang.\"\n",
    "    print_twice(line1)\n",
    "    print_twice(line2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dff2c5b",
   "metadata": {},
   "source": [
    "Calling `cat_twice()` produces the traceback below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "801d5865",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.405332Z",
     "iopub.status.busy": "2026-09-25T18:45:29.404897Z",
     "iopub.status.idle": "2026-09-25T18:45:29.409020Z",
     "shell.execute_reply": "2026-09-25T18:45:29.408154Z"
    },
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exception reporting mode: Context\n"
     ]
    }
   ],
   "source": [
    "%xmode Context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6e3c8f5a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.410438Z",
     "iopub.status.busy": "2026-09-25T18:45:29.410006Z",
     "iopub.status.idle": "2026-09-25T18:45:29.440973Z",
     "shell.execute_reply": "2026-09-25T18:45:29.440345Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bing tiddle \n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'cat' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mNameError\u001b[39m                                 Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[5]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m cat_twice()\n",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[2]\u001b[39m\u001b[32m, line 10\u001b[39m, in \u001b[36mcat_twice\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m      6\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m cat_twice():\n\u001b[32m      7\u001b[39m     \u001b[33m\"\"\"Function that calls print_twice.\"\"\"\u001b[39m\n\u001b[32m      8\u001b[39m     line1 = \u001b[33m\"Bing tiddle \"\u001b[39m\n\u001b[32m      9\u001b[39m     line2 = \u001b[33m\"tiddle bang.\"\u001b[39m\n\u001b[32m---> \u001b[39m\u001b[32m10\u001b[39m     print_twice(line1)\n\u001b[32m     11\u001b[39m     print_twice(line2)\n",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[2]\u001b[39m\u001b[32m, line 4\u001b[39m, in \u001b[36mprint_twice\u001b[39m\u001b[34m(value)\u001b[39m\n\u001b[32m      1\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m print_twice(value):\n\u001b[32m      2\u001b[39m     \u001b[33m\"\"\"Print a value twice. Contains a deliberate bug for demonstration.\"\"\"\u001b[39m\n\u001b[32m      3\u001b[39m     print(value)\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m     print(cat)          \u001b[38;5;66;03m# Bug: 'cat' is not defined\u001b[39;00m\n",
      "\u001b[31mNameError\u001b[39m: name 'cat' is not defined"
     ]
    }
   ],
   "source": [
    "%%expect NameError\n",
    "\n",
    "cat_twice()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "20b8bfe2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.442412Z",
     "iopub.status.busy": "2026-09-25T18:45:29.441966Z",
     "iopub.status.idle": "2026-09-25T18:45:29.445412Z",
     "shell.execute_reply": "2026-09-25T18:45:29.444759Z"
    },
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exception reporting mode: Minimal\n"
     ]
    }
   ],
   "source": [
    "%xmode Minimal"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86e8bb81",
   "metadata": {},
   "source": [
    "Reading this traceback from the bottom up:\n",
    "\n",
    "1. The last line says the error is a `NameError`: the name `cat` is not defined.\n",
    "2. The line above it shows the error happened at `print(cat)` inside `print_twice`.\n",
    "3. Moving up, `print_twice` was called by `cat_twice`, which was called from the notebook cell.\n",
    "4. The fix is to change `cat` to `value` in `print_twice`.\n",
    "\n",
    "Notice that the first `print(value)` ran successfully (you can see its output above the traceback) before the bug was reached."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tb-ex-intro",
   "metadata": {},
   "source": [
    "Now try it yourself. The functions below contain a different bug, and calling `checkout` raises a different kind of exception."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tb-ex-xmode-context",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "%xmode Context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tb-ex-demo",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%expect TypeError\n",
    "\n",
    "def price_of(fruit, price_table):\n",
    "    return price_table[fruit]\n",
    "\n",
    "def total_cost(cart, price_table):\n",
    "    total = \"0\"\n",
    "    for fruit in cart:\n",
    "        total += price_of(fruit, price_table)\n",
    "    return total\n",
    "\n",
    "def checkout(cart, price_table):\n",
    "    return total_cost(cart, price_table)\n",
    "\n",
    "prices = {\"apple\": 1.20, \"banana\": 0.50, \"cherry\": 3.00}\n",
    "checkout([\"apple\", \"banana\"], prices)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tb-ex-xmode-minimal",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "%xmode Minimal"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tb-ex-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Reading a Traceback\n",
    "#   The call to `checkout` above raises a TypeError.\n",
    "#   1. Read the traceback from the bottom up. What is the error message?\n",
    "#   2. Which function, and which line in it, raised the exception?\n",
    "#   3. Trace the calls upward: which function called that one?\n",
    "#   4. Find the bug and write corrected versions of the three functions below.\n",
    "#   Test:\n",
    "#     checkout([\"apple\", \"banana\"], prices)  → 1.7\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tb-ex-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "1.7\n"
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "# The last line of the traceback says: can only concatenate str (not \"float\") to str.\n",
    "# The line above it points to `total += price_of(fruit, price_table)` in total_cost,\n",
    "# which checkout called. total starts as the string \"0\" instead of the number 0,\n",
    "# so adding a float price to it fails.\n",
    "\n",
    "def price_of(fruit, price_table):\n",
    "    return price_table[fruit]\n",
    "\n",
    "def total_cost(cart, price_table):\n",
    "    total = 0\n",
    "    for fruit in cart:\n",
    "        total += price_of(fruit, price_table)\n",
    "    return total\n",
    "\n",
    "def checkout(cart, price_table):\n",
    "    return total_cost(cart, price_table)\n",
    "\n",
    "prices = {\"apple\": 1.20, \"banana\": 0.50, \"cherry\": 3.00}\n",
    "print(checkout([\"apple\", \"banana\"], prices))   # 1.7"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95ec4443",
   "metadata": {},
   "source": [
    "## Handling Exceptions\n",
    "\n",
    "Exception handling is **runtime defense**: code that runs while the program is in use to deal with conditions you expect might go wrong, such as a missing file or bad user input. It answers the question \"what should my code do when things go wrong?\"\n",
    "\n",
    "Without exception handling:\n",
    "- Programs **crash** with error messages that confuse users\n",
    "- **Users** have a poor experience\n",
    "- Problems in production are harder to **diagnose**\n",
    "\n",
    "With exception handling, you can:\n",
    "- Recover from errors and keep the program running\n",
    "- Show user-friendly error messages\n",
    "- Record errors for later debugging"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-95ec4443",
   "metadata": {},
   "source": [
    "```{index} exception handling\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e51e975",
   "metadata": {},
   "source": [
    "### `try`-`except`\n",
    "\n",
    "The `try`-`except` statement lets you catch and respond to exceptions instead of letting them crash your program. You wrap the risky code in a `try` block; if an exception is raised, Python jumps immediately to the matching `except` block and executes it instead.\n",
    "\n",
    "**Syntax:**\n",
    "```python\n",
    "try:\n",
    "    # Code that might raise an exception\n",
    "    risky_code()\n",
    "except ExceptionType:\n",
    "    # Handle the exception\n",
    "    handle_error()\n",
    "```\n",
    "\n",
    "A complete `try` statement can include up to four clauses, each serving a distinct role:\n",
    "\n",
    "- **`try`**: Block containing code that might raise an exception\n",
    "- **`except`**: Block to handle specific exception type(s)\n",
    "- **`else`** (optional): Block that executes if no exception occurs\n",
    "- **`finally`** (optional): Block that always executes, regardless of exception\n",
    "\n",
    "This part starts with `try` and `except`; `else` and `finally` are covered in {ref}`else and finally <ch05-else-finally>`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-3e51e975",
   "metadata": {},
   "source": [
    "```{index} try statement, except clause\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b7779127",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.446848Z",
     "iopub.status.busy": "2026-09-25T18:45:29.446401Z",
     "iopub.status.idle": "2026-09-25T18:45:29.450019Z",
     "shell.execute_reply": "2026-09-25T18:45:29.449401Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error: Cannot divide by zero!\n"
     ]
    }
   ],
   "source": [
    "# Example 1: Simple try-except\n",
    "\n",
    "try:\n",
    "    result = 10 / 0\n",
    "    print(f\"Result: {result}\")\n",
    "except ZeroDivisionError:\n",
    "    print(\"Error: Cannot divide by zero!\")   ### program does not crash; error is handled"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "760fa480",
   "metadata": {},
   "source": [
    "In this example, dividing by zero raises a `ZeroDivisionError`. Python skips the rest of the `try` block (so `Result:` is never printed), runs the `except` clause, and the program continues instead of crashing."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "88818fad",
   "metadata": {},
   "source": [
    "### Accessing the Exception Object (`as e`)\n",
    "\n",
    "Adding `as e` to an `except` clause binds the exception object to the variable `e`, so you can inspect it:\n",
    "\n",
    "```python\n",
    "except ValueError as e:\n",
    "    print(e)           # prints the error message\n",
    "    print(type(e))     # <class 'ValueError'>\n",
    "```\n",
    "\n",
    "`e` is just a conventional name; you could use any variable name (`as err`, `as exc`, etc.). Inside an f-string, `{e}` calls `str(e)`, which produces the human-readable error message:\n",
    "\n",
    "```python\n",
    "except FileNotFoundError as e:\n",
    "    print(f\"Error: {e}\")   # e.g. \"Error: [Errno 2] No such file or directory: 'x.txt'\"\n",
    "```\n",
    "\n",
    "You can omit `as e` entirely when you don't need the details:\n",
    "\n",
    "```python\n",
    "except ZeroDivisionError:\n",
    "    print(\"Cannot divide by zero\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-88818fad",
   "metadata": {},
   "source": [
    "```{index} exception object, except clause\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3b46e3ac",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.451046Z",
     "iopub.status.busy": "2026-09-25T18:45:29.450933Z",
     "iopub.status.idle": "2026-09-25T18:45:29.453592Z",
     "shell.execute_reply": "2026-09-25T18:45:29.452952Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Catching Exceptions\n",
    "#   Write `safe_int(s)` that:\n",
    "#   1. Tries to convert the string `s` to an integer with `int(s)`.\n",
    "#   2. Returns the integer if conversion succeeds.\n",
    "#   3. If `s` cannot be converted, catches the exception, prints a descriptive\n",
    "#      message, and returns None.\n",
    "#   Test:\n",
    "#     safe_int('42')   → 42\n",
    "#     safe_int('3.14') → None  (prints a message)\n",
    "#     safe_int('abc')  → None  (prints a message)\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "599ebb47-1cc8-4914-83ec-6f6aa1f0e3bf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.454624Z",
     "iopub.status.busy": "2026-09-25T18:45:29.454470Z",
     "iopub.status.idle": "2026-09-25T18:45:29.458275Z",
     "shell.execute_reply": "2026-09-25T18:45:29.457376Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "42\n",
      "Cannot convert '3.14' to int\n",
      "None\n",
      "Cannot convert 'abc' to int\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "def safe_int(s):\n",
    "    try:\n",
    "        return int(s)\n",
    "    except ValueError:\n",
    "        print(f\"Cannot convert {s!r} to int\")\n",
    "        return None\n",
    "\n",
    "print(safe_int('42'))    # 42\n",
    "print(safe_int('3.14'))  # message, then None\n",
    "print(safe_int('abc'))   # message, then None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1348562e",
   "metadata": {},
   "source": [
    "### Handling Multiple Exceptions\n",
    "\n",
    "You can handle multiple exception types in a single `try` statement using several approaches:\n",
    "\n",
    "1. **Multiple `except` blocks**: Handle each exception type differently. This is the preferred approach, because it lets you respond to each specific problem.\n",
    "2. **Single `except` with a tuple**: Handle several types the same way (e.g., `except (ValueError, TypeError):`).\n",
    "3. **Generic `except`**: Catch any exception. Use this cautiously, because it can hide bugs.\n",
    "\n",
    "The best practice is to catch specific exceptions first and use a generic `except Exception` only as a last resort for truly unexpected errors.\n",
    "\n",
    "A **generic except** can be written in two ways:\n",
    "\n",
    "Option 1: bare `except` (catches absolutely everything, including `SystemExit` and `KeyboardInterrupt`)\n",
    "```python\n",
    "try:\n",
    "    risky_code()\n",
    "except:\n",
    "    print(\"Something went wrong\")\n",
    "```\n",
    "Option 2: `except Exception` (preferred; catches all normal errors but not system exits)\n",
    "```python\n",
    "try:\n",
    "    risky_code()\n",
    "except Exception as e:\n",
    "    print(f\"Error: {type(e).__name__}: {e}\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-1348562e",
   "metadata": {},
   "source": [
    "```{index} multiple except clauses\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff926be9",
   "metadata": {},
   "source": [
    ":::{dropdown} What is `__name__`?\n",
    "Every class has a special built-in attribute `__name__` that holds its name as a plain string. (Functions and modules have one too.) Because every type is a class, `type(x).__name__` gives you the readable name of a value's type:\n",
    "\n",
    "    type(42).__name__       # 'int'\n",
    "    type(\"hello\").__name__  # 'str'\n",
    "    type(3.14).__name__     # 'float'\n",
    "    type(None).__name__     # 'NoneType'\n",
    "\n",
    "In exception handling you often use it to produce a readable error message without hard-coding a type name:\n",
    "\n",
    "    if not isinstance(age, (int, float)):\n",
    "        raise TypeError(f\"Age must be a number, got {type(age).__name__}\")\n",
    "\n",
    "If someone passes `\"twenty\"`, the message reads `\"Age must be a number, got str\"` rather than `\"Age must be a number, got <class 'str'>\"`.\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf464088",
   "metadata": {},
   "source": [
    "The example below uses multiple `except` blocks. It also uses `raise ValueError(...)` to signal an unknown operation; `raise` is covered in {ref}`Raising Exceptions <ch05-raising-exceptions>`, and for now it is enough to know that it triggers an exception on purpose."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "06a269f3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.460070Z",
     "iopub.status.busy": "2026-09-25T18:45:29.459494Z",
     "iopub.status.idle": "2026-09-25T18:45:29.466074Z",
     "shell.execute_reply": "2026-09-25T18:45:29.465232Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Testing calculator with error handling:\n",
      "10 add 5 = 15.0\n",
      "----------------------------------------\n",
      "ValueError: could not convert string to float: 'abc'\n",
      "----------------------------------------\n",
      "ZeroDivisionError: Division by zero is not allowed\n",
      "----------------------------------------\n",
      "ValueError: Unknown operation: power\n",
      "----------------------------------------\n"
     ]
    }
   ],
   "source": [
    "# Example 2: Multiple exception handling approaches\n",
    "\n",
    "def calculate_from_strings(num1_str, num2_str, operation):\n",
    "    \"\"\"Perform calculations with comprehensive error handling.\"\"\"\n",
    "    \n",
    "    try:\n",
    "        # Convert strings to numbers\n",
    "        num1 = float(num1_str)\n",
    "        num2 = float(num2_str)\n",
    "        \n",
    "        # Perform the requested operation\n",
    "        if operation == 'add':\n",
    "            result = num1 + num2\n",
    "        elif operation == 'subtract':\n",
    "            result = num1 - num2\n",
    "        elif operation == 'multiply':\n",
    "            result = num1 * num2\n",
    "        elif operation == 'divide':\n",
    "            result = num1 / num2\n",
    "        else:\n",
    "            raise ValueError(f\"Unknown operation: {operation}\")\n",
    "            \n",
    "        return result\n",
    "        \n",
    "    except ValueError as e:\n",
    "        print(f\"ValueError: {e}\")\n",
    "        return None\n",
    "    except ZeroDivisionError:\n",
    "        print(\"ZeroDivisionError: Division by zero is not allowed\")\n",
    "        return None\n",
    "    except Exception as e:      ### general catch-all for unexpected exceptions\n",
    "        print(f\"Unexpected error: {type(e).__name__}: {e}\")\n",
    "        return None\n",
    "\n",
    "# Test different scenarios\n",
    "test_cases = [\n",
    "    (\"10\", \"5\", \"add\"),       # Valid\n",
    "    (\"10\", \"abc\", \"add\"),     # ValueError (invalid number)\n",
    "    (\"10\", \"0\", \"divide\"),    # ZeroDivisionError\n",
    "    (\"10\", \"5\", \"power\"),     # ValueError (unknown operation)\n",
    "]\n",
    "\n",
    "print(\"Testing calculator with error handling:\")\n",
    "for num1, num2, op in test_cases:\n",
    "    result = calculate_from_strings(num1, num2, op)\n",
    "    if result is not None:\n",
    "        print(f\"{num1} {op} {num2} = {result}\")\n",
    "    print(\"-\" * 40)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "be25fa11",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.467412Z",
     "iopub.status.busy": "2026-09-25T18:45:29.467274Z",
     "iopub.status.idle": "2026-09-25T18:45:29.470355Z",
     "shell.execute_reply": "2026-09-25T18:45:29.469637Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Multiple Exception Types\n",
    "#   Write `safe_index(lst, i)` that:\n",
    "#   1. Returns lst[i] if the access succeeds.\n",
    "#   2. Catches IndexError (index out of range): prints a message and returns None.\n",
    "#   3. Catches TypeError (non-integer index): prints a message and returns None.\n",
    "#   Test:\n",
    "#     safe_index([10, 20, 30], 1)   → 20\n",
    "#     safe_index([10, 20, 30], 9)   → None  (IndexError)\n",
    "#     safe_index([10, 20, 30], 'a') → None  (TypeError)\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4bf3d7be-fdc8-4035-b29e-0ab11da1e133",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.471642Z",
     "iopub.status.busy": "2026-09-25T18:45:29.471448Z",
     "iopub.status.idle": "2026-09-25T18:45:29.476361Z",
     "shell.execute_reply": "2026-09-25T18:45:29.475502Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "Index 9 is out of range for a list of length 3\n",
      "None\n",
      "Index must be an integer, got str\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "def safe_index(lst, i):\n",
    "    try:\n",
    "        return lst[i]\n",
    "    except IndexError:\n",
    "        print(f\"Index {i} is out of range for a list of length {len(lst)}\")\n",
    "        return None\n",
    "    except TypeError:\n",
    "        print(f\"Index must be an integer, got {type(i).__name__}\")\n",
    "        return None\n",
    "\n",
    "print(safe_index([10, 20, 30], 1))    # 20\n",
    "print(safe_index([10, 20, 30], 9))    # message, then None\n",
    "print(safe_index([10, 20, 30], 'a'))  # message, then None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d361fdc",
   "metadata": {},
   "source": [
    "(ch05-else-finally)=\n",
    "### `else` and `finally`\n",
    "\n",
    "The `try` statement can include `else` and `finally` blocks for additional control:\n",
    "\n",
    "- **`else` block**: Runs only if NO exception occurred in the `try` block\n",
    "- **`finally` block**: ALWAYS runs, whether an exception occurred or not\n",
    "\n",
    "Putting success-only code in `else` (rather than at the end of `try`) keeps the `try` block small, so you don't accidentally catch exceptions from code you didn't mean to protect. `finally` is the place for cleanup, such as closing files or connections.\n",
    "\n",
    "**Complete Syntax:**\n",
    "```python\n",
    "try:\n",
    "    # Code that might raise an exception\n",
    "    risky_code()\n",
    "except SpecificException:\n",
    "    # Handle specific exception\n",
    "    handle_error()\n",
    "else:\n",
    "    # Code that runs only if no exception occurred\n",
    "    success_code()\n",
    "finally:\n",
    "    # Code that always runs (cleanup)\n",
    "    cleanup_code()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-9d361fdc",
   "metadata": {},
   "source": [
    "```{index} else clause (try), finally clause\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f6729ec3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.478095Z",
     "iopub.status.busy": "2026-09-25T18:45:29.477534Z",
     "iopub.status.idle": "2026-09-25T18:45:29.483223Z",
     "shell.execute_reply": "2026-09-25T18:45:29.482460Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Processing file: document.txt\n",
      "Successfully opened document.txt\n",
      "File processed successfully!\n",
      "Data length: 24\n",
      "Cleaning up resources...\n",
      "File processor finished\n",
      "Returned: Contents of document.txt\n",
      "==================================================\n",
      "\n",
      "Processing file: missing.txt\n",
      "File error: File does not exist\n",
      "Cleaning up resources...\n",
      "File processor finished\n",
      "Returned: None\n",
      "==================================================\n",
      "\n",
      "Processing file: corrupted.txt\n",
      "Data error: File is corrupted\n",
      "Cleaning up resources...\n",
      "File processor finished\n",
      "Returned: None\n",
      "==================================================\n"
     ]
    }
   ],
   "source": [
    "# Example 3: Using else and finally blocks\n",
    "\n",
    "def file_processor(filename):\n",
    "    \"\"\"Demonstrate else and finally blocks.\"\"\"\n",
    "    print(f\"\\nProcessing file: {filename}\")\n",
    "    \n",
    "    try:\n",
    "        # Simulate file processing\n",
    "        if filename == \"missing.txt\":\n",
    "            raise FileNotFoundError(\"File does not exist\")\n",
    "        elif filename == \"corrupted.txt\":\n",
    "            raise ValueError(\"File is corrupted\")\n",
    "        else:\n",
    "            print(f\"Successfully opened {filename}\")\n",
    "            data = f\"Contents of {filename}\"\n",
    "            \n",
    "    except FileNotFoundError as e:\n",
    "        print(f\"File error: {e}\")\n",
    "        data = None\n",
    "    except ValueError as e:\n",
    "        print(f\"Data error: {e}\")\n",
    "        data = None\n",
    "    else:\n",
    "        # This runs only if no exception occurred\n",
    "        print(\"File processed successfully!\")\n",
    "        print(f\"Data length: {len(data)}\")\n",
    "    finally:\n",
    "        # This always runs\n",
    "        print(\"Cleaning up resources...\")\n",
    "        print(\"File processor finished\")\n",
    "    \n",
    "    return data\n",
    "\n",
    "# Test different scenarios\n",
    "test_files = [\"document.txt\", \"missing.txt\", \"corrupted.txt\"]\n",
    "\n",
    "for filename in test_files:\n",
    "    result = file_processor(filename)\n",
    "    print(f\"Returned: {result}\")\n",
    "    print(\"=\" * 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "843fc6c6",
   "metadata": {},
   "source": [
    "Example 3 simulates its errors. The next example puts all four clauses together on a real file operation.\n",
    "\n",
    "Its second `except` clause catches `OSError`, the built-in exception Python raises for file and operating-system problems, such as a file you do not have permission to read. `FileNotFoundError` is a more specific kind of `OSError`, so its clause comes first. In older code you may see `except IOError`; `IOError` is simply an older name for `OSError`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "9f196214",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.484951Z",
     "iopub.status.busy": "2026-09-25T18:45:29.484376Z",
     "iopub.status.idle": "2026-09-25T18:45:29.489375Z",
     "shell.execute_reply": "2026-09-25T18:45:29.488606Z"
    }
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Error: File 'non_existent_file.txt' not found!\n",
      "File operation finished.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Example 4: Practical example - safe file handling\n",
    "def read_file_safely(filename):\n",
    "    content = None\n",
    "    try:\n",
    "        # `with open(...)` opens the file and closes it automatically when the block ends\n",
    "        with open(filename, \"r\") as file:\n",
    "            content = file.read()\n",
    "            print(f\"File '{filename}' content:\\n{content}\")\n",
    "    except FileNotFoundError:    ### occurs if the file does not exist\n",
    "        print(f\"Error: File '{filename}' not found!\")\n",
    "    except OSError as e:         ### any other file problem (IOError is an older name for OSError)\n",
    "        print(f\"Error reading file: {e}\")\n",
    "    else:\n",
    "        print(\"File reading completed successfully.\")\n",
    "    finally:\n",
    "        print(\"File operation finished.\\n\")\n",
    "    return content\n",
    "\n",
    "read_file_safely(\"non_existent_file.txt\")  # triggers FileNotFoundError\n",
    "# read_file_safely(\"../../data/words.txt\")  # uncomment to read an existing file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ee87865c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.490702Z",
     "iopub.status.busy": "2026-09-25T18:45:29.490513Z",
     "iopub.status.idle": "2026-09-25T18:45:29.493467Z",
     "shell.execute_reply": "2026-09-25T18:45:29.492723Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Safe Division with Cleanup\n",
    "#   Write `safe_divide(a, b)` that:\n",
    "#   1. Returns the result of `a / b`.\n",
    "#   2. If `b` is zero, prints \"Error: cannot divide by zero\" and returns None.\n",
    "#   3. Always prints \"Operation complete.\" in a `finally` block, regardless of outcome.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "6591566b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.494743Z",
     "iopub.status.busy": "2026-09-25T18:45:29.494600Z",
     "iopub.status.idle": "2026-09-25T18:45:29.498845Z",
     "shell.execute_reply": "2026-09-25T18:45:29.498070Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Operation complete.\n",
      "5.0\n",
      "Error: cannot divide by zero\n",
      "Operation complete.\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "def safe_divide(a, b):\n",
    "    try:\n",
    "        result = a / b\n",
    "    except ZeroDivisionError:\n",
    "        print(\"Error: cannot divide by zero\")\n",
    "        result = None\n",
    "    finally:\n",
    "        print(\"Operation complete.\")\n",
    "    return result\n",
    "\n",
    "print(safe_divide(10, 2))   # \"Operation complete.\" prints first, then 5.0\n",
    "print(safe_divide(5, 0))    # error message, \"Operation complete.\", then None"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e3a8472",
   "metadata": {},
   "source": [
    "Notice that `Operation complete.` appears *before* `5.0`. The `finally` block runs when the function finishes, and only then does `print()` receive the returned value."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab9d01c4",
   "metadata": {},
   "source": [
    "(ch05-raising-exceptions)=\n",
    "## Raising Exceptions\n",
    "\n",
    "So far, Python has raised the exceptions for you: `int(\"abc\")` raises a `ValueError` automatically. You can also raise exceptions yourself with the `raise` statement, to tell the caller that something is wrong.\n",
    "\n",
    "**Syntax:**\n",
    "```python\n",
    "raise ExceptionType(\"Error message\")\n",
    "```\n",
    "\n",
    "Raising an exception pushes the decision about what to do up to the caller, which is usually better than returning `None` or a \"magic value\" like `-1` that the caller might forget to check. Raising is **detection** work; catching the exception in the caller is **handling**.\n",
    "\n",
    "In most cases, you should raise one of Python's built-in types (`ValueError`, `TypeError`, `RuntimeError`, and so on) rather than the generic `Exception`. Pick the type that describes the problem: `TypeError` for a value of the wrong type, `ValueError` for a value of the right type but an invalid content.\n",
    "\n",
    "In the code below, `divide` detects the problem and the caller handles it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ab9d01c4",
   "metadata": {},
   "source": [
    "```{index} raise statement\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "8bb4e56f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.500593Z",
     "iopub.status.busy": "2026-09-25T18:45:29.499971Z",
     "iopub.status.idle": "2026-09-25T18:45:29.504432Z",
     "shell.execute_reply": "2026-09-25T18:45:29.503637Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b cannot be zero\n"
     ]
    }
   ],
   "source": [
    "def divide(a, b):\n",
    "    if b == 0:\n",
    "        raise ValueError(\"b cannot be zero\")\n",
    "    return a / b\n",
    "\n",
    "try:\n",
    "    result = divide(10, 0)\n",
    "except ValueError as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "349d752c",
   "metadata": {},
   "source": [
    "**Common scenarios for raising exceptions:**\n",
    "- Input validation fails\n",
    "- Business rules are violated\n",
    "- Resources are unavailable\n",
    "- An object is in an invalid state"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "fa8cae85",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.506179Z",
     "iopub.status.busy": "2026-09-25T18:45:29.505631Z",
     "iopub.status.idle": "2026-09-25T18:45:29.510949Z",
     "shell.execute_reply": "2026-09-25T18:45:29.509969Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Valid age: 25\n",
      "Validation failed for -5: Age cannot be negative\n",
      "Validation failed for 200: Age cannot be greater than 150\n",
      "Validation failed for twenty: Age must be a number, got str\n",
      "Valid age: 45.5\n",
      "Validation failed for None: Age must be a number, got NoneType\n"
     ]
    }
   ],
   "source": [
    "# Example 5: Raising exceptions for input validation\n",
    "\n",
    "def validate_age(age):\n",
    "    \"\"\"Validate age input by raising built-in exceptions.\"\"\"\n",
    "    if not isinstance(age, (int, float)):\n",
    "        raise TypeError(f\"Age must be a number, got {type(age).__name__}\")\n",
    "    \n",
    "    if age < 0:\n",
    "        raise ValueError(\"Age cannot be negative\")\n",
    "    \n",
    "    if age > 150:\n",
    "        raise ValueError(\"Age cannot be greater than 150\")\n",
    "    \n",
    "    print(f\"Valid age: {age}\")\n",
    "    return age\n",
    "\n",
    "# Test age validation\n",
    "test_ages = [25, -5, 200, \"twenty\", 45.5, None]\n",
    "\n",
    "for age in test_ages:\n",
    "    try:\n",
    "        validate_age(age)\n",
    "    except (TypeError, ValueError) as e:\n",
    "        print(f\"Validation failed for {age}: {e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "23709533",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.512669Z",
     "iopub.status.busy": "2026-09-25T18:45:29.511923Z",
     "iopub.status.idle": "2026-09-25T18:45:29.515316Z",
     "shell.execute_reply": "2026-09-25T18:45:29.514541Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Raising Exceptions\n",
    "#   Write `square_root(x)` that:\n",
    "#   1. Raises a `TypeError` with a descriptive message if x is not a number (int or float).\n",
    "#   2. Raises a `ValueError` with a descriptive message if x < 0.\n",
    "#   3. Otherwise returns x ** 0.5.\n",
    "#   Test:\n",
    "#     square_root(9)       → 3.0\n",
    "#     square_root(-4)      → raises ValueError\n",
    "#     square_root(\"nine\")  → raises TypeError\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "5accaea9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.517132Z",
     "iopub.status.busy": "2026-09-25T18:45:29.516542Z",
     "iopub.status.idle": "2026-09-25T18:45:29.521669Z",
     "shell.execute_reply": "2026-09-25T18:45:29.520865Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.0\n",
      "ValueError: Cannot take square root of negative number: -4\n",
      "TypeError: Expected a number, got str\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "def square_root(x):\n",
    "    if not isinstance(x, (int, float)):\n",
    "        raise TypeError(f\"Expected a number, got {type(x).__name__}\")\n",
    "    if x < 0:\n",
    "        raise ValueError(f\"Cannot take square root of negative number: {x}\")\n",
    "    return x ** 0.5\n",
    "\n",
    "print(square_root(9))        # 3.0\n",
    "\n",
    "try:\n",
    "    square_root(-4)\n",
    "except ValueError as e:\n",
    "    print(f\"ValueError: {e}\")\n",
    "\n",
    "try:\n",
    "    square_root(\"nine\")\n",
    "except TypeError as e:\n",
    "    print(f\"TypeError: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee19715d",
   "metadata": {},
   "source": [
    "### Type Hints Are Not Runtime Checks\n",
    "\n",
    "Type hints describe what a function expects, but they are not runtime validation. If you annotate a parameter as `int`, Python will still let someone pass a string unless your code checks for it and raises an exception.\n",
    "\n",
    "```python\n",
    "def double(n: int) -> int:\n",
    "    return n * 2\n",
    "\n",
    "print(double(\"ha\"))   # Python allows this; the result is \"haha\"\n",
    "```\n",
    "\n",
    "There are three different ideas that are easy to confuse:\n",
    "\n",
    "| Technique | When it runs | What it does |\n",
    "|---|---|---|\n",
    "| Type hints | Not enforced by Python itself | Documents expected types |\n",
    "| `mypy` or another static checker | Before the program runs | Reports likely type mistakes |\n",
    "| Runtime checks | While the program runs | Raises errors or handles bad values |\n",
    "\n",
    "A static checker such as `mypy` can warn that a call probably violates the function contract:\n",
    "\n",
    "```bash\n",
    "mypy my_program.py\n",
    "```\n",
    "\n",
    "Runtime checks are regular Python code: an `if` test followed by `raise`. Use them when invalid input must be rejected while the program is running."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ee19715d",
   "metadata": {},
   "source": [
    "```{index} type hint, runtime check, mypy\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "type-checks-02",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.522756Z",
     "iopub.status.busy": "2026-09-25T18:45:29.522620Z",
     "iopub.status.idle": "2026-09-25T18:45:29.526863Z",
     "shell.execute_reply": "2026-09-25T18:45:29.526135Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20.0\n"
     ]
    }
   ],
   "source": [
    "def average(numbers: list[float]) -> float:\n",
    "    if not isinstance(numbers, list):\n",
    "        raise TypeError(f\"numbers must be a list, got {type(numbers).__name__}\")\n",
    "    if len(numbers) == 0:\n",
    "        raise ValueError(\"numbers must not be empty\")\n",
    "    return sum(numbers) / len(numbers)\n",
    "\n",
    "print(average([10.0, 20.0, 30.0]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "type-checks-03",
   "metadata": {},
   "source": [
    "Use type hints to make intent clear. Use tests to verify behavior. Use runtime checks and exceptions only when the program needs to defend itself against invalid data while it is running.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ece7b9e6",
   "metadata": {},
   "source": [
    "### Custom Exception Classes\n",
    "\n",
    "When no built-in type describes your problem well, you can define your own exception type by creating a class that inherits from `Exception`. Callers can then catch your specific error separately from everything else.\n",
    "\n",
    ":::{note}\n",
    "The example below uses classes, which are covered in the OOP chapter. You can skim it now and come back to it after that chapter.\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ece7b9e6",
   "metadata": {},
   "source": [
    "```{index} custom exception\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "186e59ef",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.528188Z",
     "iopub.status.busy": "2026-09-25T18:45:29.527976Z",
     "iopub.status.idle": "2026-09-25T18:45:29.534014Z",
     "shell.execute_reply": "2026-09-25T18:45:29.533273Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Testing bank account:\n",
      "Deposited $50. New balance: $150\n",
      "Withdrew $30. New balance: $120\n",
      "Banking error: Insufficient funds: balance=$120, requested=$200\n"
     ]
    }
   ],
   "source": [
    "# Example 6: Custom exception classes\n",
    "class InsufficientFundsError(Exception):\n",
    "    \"\"\"Raised when a withdrawal exceeds the current balance.\"\"\"\n",
    "    pass\n",
    "\n",
    "class BankAccount:\n",
    "    \"\"\"Simple bank account with exception handling.\"\"\"\n",
    "    \n",
    "    def __init__(self, initial_balance=0):\n",
    "        if initial_balance < 0:\n",
    "            raise ValueError(\"Initial balance cannot be negative\")\n",
    "        self.balance = initial_balance\n",
    "    \n",
    "    def deposit(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"Deposit amount must be positive\")\n",
    "        self.balance += amount\n",
    "        print(f\"Deposited ${amount}. New balance: ${self.balance}\")\n",
    "    \n",
    "    def withdraw(self, amount):\n",
    "        if amount <= 0:\n",
    "            raise ValueError(\"Withdrawal amount must be positive\")\n",
    "        if amount > self.balance:\n",
    "            raise InsufficientFundsError(\n",
    "                f\"Insufficient funds: balance=${self.balance}, requested=${amount}\"\n",
    "            )\n",
    "        self.balance -= amount\n",
    "        print(f\"Withdrew ${amount}. New balance: ${self.balance}\")\n",
    "    \n",
    "    def get_balance(self):\n",
    "        return self.balance\n",
    "\n",
    "# Test the bank account\n",
    "print(\"Testing bank account:\")\n",
    "try:\n",
    "    account = BankAccount(100)\n",
    "    account.deposit(50)\n",
    "    account.withdraw(30)\n",
    "    account.withdraw(200)  # This will raise InsufficientFundsError\n",
    "\n",
    "except ValueError as e:\n",
    "    print(f\"Input error: {e}\")\n",
    "except InsufficientFundsError as e:\n",
    "    print(f\"Banking error: {e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "custom-exc-exercise",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Custom Exception Class\n",
    "#   1. Define an exception class `OutOfStockError` that inherits from `Exception`.\n",
    "#      The body needs only `pass`, like `InsufficientFundsError` above.\n",
    "#   2. Write a function `buy_fruit(fruit, inventory)` that:\n",
    "#      - raises `OutOfStockError` with a descriptive message if inventory[fruit] is 0\n",
    "#      - otherwise subtracts 1 from inventory[fruit] and returns the new count\n",
    "#   3. Call `buy_fruit` inside `try` and catch `OutOfStockError` by name.\n",
    "#   Test:\n",
    "#     inventory = {\"apple\": 2, \"banana\": 0, \"cherry\": 5}\n",
    "#     buy_fruit(\"apple\", inventory)   → 1\n",
    "#     buy_fruit(\"banana\", inventory)  → raises OutOfStockError\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "custom-exc-solution",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "1\nOutOfStockError: Sorry, banana is out of stock\n"
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "class OutOfStockError(Exception):\n",
    "    pass\n",
    "\n",
    "def buy_fruit(fruit, inventory):\n",
    "    if inventory[fruit] == 0:\n",
    "        raise OutOfStockError(f\"Sorry, {fruit} is out of stock\")\n",
    "    inventory[fruit] -= 1\n",
    "    return inventory[fruit]\n",
    "\n",
    "inventory = {\"apple\": 2, \"banana\": 0, \"cherry\": 5}\n",
    "print(buy_fruit(\"apple\", inventory))   # 1\n",
    "\n",
    "try:\n",
    "    buy_fruit(\"banana\", inventory)\n",
    "except OutOfStockError as e:\n",
    "    print(f\"OutOfStockError: {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0a61fb5f",
   "metadata": {},
   "source": [
    "## Debugging\n",
    "\n",
    "Exceptions tell you *that* something went wrong. Finding out *why* is **debugging**. Debugging can be frustrating, but it is also challenging, interesting, and sometimes even fun. It is one of the most important skills you can learn.\n",
    "\n",
    "**Debugging is like detective work**: You are given clues, and you have to infer the events that led to the results you see.\n",
    "\n",
    "**Debugging is like experimental science**: Once you have an idea about what is going wrong, you modify your program and try again. If your hypothesis was correct, you can predict the result of the modification. If your hypothesis was wrong, you have to come up with a new one.\n",
    "\n",
    "**Key debugging principles:**\n",
    "- Start with a working program and make small modifications\n",
    "- Test frequently; don't write too much code before testing\n",
    "- Read error messages and tracebacks carefully\n",
    "- Think systematically about what could be wrong\n",
    "\n",
    "If you find yourself spending a lot of time debugging, that's often a sign you're writing too much code before testing. Taking smaller steps can help you move more quickly.\n",
    "\n",
    "The rest of this part covers three practical techniques: print-statement debugging, assertions, and systematic bisection."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-0a61fb5f",
   "metadata": {},
   "source": [
    "```{index} debugging\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "390c7312",
   "metadata": {},
   "source": [
    "### Print-Statement Debugging\n",
    "\n",
    "Insert temporary `print()` calls to inspect variable values and confirm which lines of code are actually running. Prefix them with `DEBUG:` so they are easy to find and remove later. This is the simplest technique and works well for most everyday bugs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-390c7312",
   "metadata": {},
   "source": [
    "```{index} print debugging\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "442b4dc5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.535631Z",
     "iopub.status.busy": "2026-09-25T18:45:29.535112Z",
     "iopub.status.idle": "2026-09-25T18:45:29.540196Z",
     "shell.execute_reply": "2026-09-25T18:45:29.539437Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Print Statement Debugging ===\n",
      "DEBUG: Input numbers = [10, 20, 30, 40]\n",
      "DEBUG: Length = 4\n",
      "DEBUG: Step 1: added 10, total now = 10\n",
      "DEBUG: Step 2: added 20, total now = 30\n",
      "DEBUG: Step 3: added 30, total now = 60\n",
      "DEBUG: Step 4: added 40, total now = 100\n",
      "DEBUG: Final average = 25.0\n",
      "Result: 25.0\n"
     ]
    }
   ],
   "source": [
    "def debug_with_print_statements():\n",
    "    \"\"\"Demonstrate print statement debugging.\"\"\"\n",
    "    print(\"=== Print Statement Debugging ===\")\n",
    "    \n",
    "    def calculate_average(numbers):\n",
    "        print(f\"DEBUG: Input numbers = {numbers}\")\n",
    "        print(f\"DEBUG: Length = {len(numbers)}\")\n",
    "        \n",
    "        total = 0\n",
    "        for i, num in enumerate(numbers):\n",
    "            total += num\n",
    "            print(f\"DEBUG: Step {i+1}: added {num}, total now = {total}\")\n",
    "        \n",
    "        average = total / len(numbers)\n",
    "        print(f\"DEBUG: Final average = {average}\")\n",
    "        return average\n",
    "    \n",
    "    # Test with example data\n",
    "    test_numbers = [10, 20, 30, 40]\n",
    "    result = calculate_average(test_numbers)\n",
    "    print(f\"Result: {result}\")\n",
    "\n",
    "debug_with_print_statements()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5568976",
   "metadata": {},
   "source": [
    "### Assertions\n",
    "\n",
    "Use `assert` to document assumptions your code makes (e.g., \"this argument must be a non-negative integer\"). If the assumption is ever violated, Python raises an `AssertionError` immediately at the offending line rather than silently producing a wrong result later.\n",
    "\n",
    "The syntax of `assert` is:\n",
    "```python\n",
    "assert condition\n",
    "assert condition, \"message shown if condition is False\"\n",
    "```\n",
    "For example,"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-b5568976",
   "metadata": {},
   "source": [
    "```{index} assert statement, AssertionError\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "e0db2d20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.541494Z",
     "iopub.status.busy": "2026-09-25T18:45:29.541359Z",
     "iopub.status.idle": "2026-09-25T18:45:29.545820Z",
     "shell.execute_reply": "2026-09-25T18:45:29.545054Z"
    }
   },
   "outputs": [
    {
     "ename": "AssertionError",
     "evalue": "Expected int, got float",
     "output_type": "error",
     "traceback": [
      "\u001b[31mAssertionError\u001b[39m\u001b[31m:\u001b[39m Expected int, got float\n"
     ]
    }
   ],
   "source": [
    "%%expect AssertionError\n",
    "\n",
    "items = [\"Alarm Clock\", \"Backpack\", \"Candle\", \"Doll\"]\n",
    "n = 42.0\n",
    "\n",
    "assert 2 + 2 == 4               # passes silently\n",
    "assert len(items) > 0           # passes if list is non-empty\n",
    "\n",
    "assert isinstance(n, int), f\"Expected int, got {type(n).__name__}\" ### fails w/ message"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "469662bf",
   "metadata": {},
   "source": [
    "Assertions are for *developer* checks, and they can be switched off. If you run Python with the `-O` flag (`python -O myscript.py`), every `assert` in your program is silently skipped. For that reason, never use `assert` to validate user input or other data your program must reject. Compare `assert` with `raise`:\n",
    "\n",
    "- `assert`: \"this should never be False if my code is correct\" (catching your own bugs during development)\n",
    "- `raise`: \"this input is invalid and I need to handle it\" (defending against bad data at runtime)\n",
    "\n",
    "The example below uses assertions to check a function's assumptions and an intermediate result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "6fd8d26d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.547378Z",
     "iopub.status.busy": "2026-09-25T18:45:29.546901Z",
     "iopub.status.idle": "2026-09-25T18:45:29.552309Z",
     "shell.execute_reply": "2026-09-25T18:45:29.551572Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== Assertion Debugging ===\n",
      "Computing factorial of 5\n",
      "factorial(5) = 120\n",
      "Computing factorial of 0\n",
      "factorial(0) = 1\n",
      "Computing factorial of 1\n",
      "factorial(1) = 1\n"
     ]
    }
   ],
   "source": [
    "def debug_with_assertions():\n",
    "    \"\"\"Demonstrate assertion debugging.\"\"\"\n",
    "    print(\"=== Assertion Debugging ===\")\n",
    "    \n",
    "    def factorial(n):\n",
    "        # Assertions help catch problems early\n",
    "        assert isinstance(n, int), f\"Expected int, got {type(n).__name__}\"\n",
    "        assert n >= 0, f\"Expected non-negative number, got {n}\"\n",
    "        \n",
    "        print(f\"Computing factorial of {n}\")\n",
    "        \n",
    "        if n == 0 or n == 1:\n",
    "            return 1\n",
    "        \n",
    "        result = 1\n",
    "        for i in range(2, n + 1):\n",
    "            result *= i\n",
    "            # Assertion to check intermediate results\n",
    "            assert result > 0, f\"Unexpected negative result at step {i}\"\n",
    "        \n",
    "        return result\n",
    "    \n",
    "    # Test cases\n",
    "    ### add -10 to test_cases to see an assertion fail\n",
    "    test_cases = [5, 0, 1]\n",
    "    for test in test_cases:\n",
    "        try:\n",
    "            result = factorial(test)\n",
    "            print(f\"factorial({test}) = {result}\")\n",
    "        except AssertionError as e:\n",
    "            print(f\"Assertion failed for factorial({test}): {e}\")\n",
    "\n",
    "debug_with_assertions()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "942df1b0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.553628Z",
     "iopub.status.busy": "2026-09-25T18:45:29.553445Z",
     "iopub.status.idle": "2026-09-25T18:45:29.556544Z",
     "shell.execute_reply": "2026-09-25T18:45:29.555775Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Using Assertions\n",
    "#   Add assert statements to `validate_triangle(a, b, c)` that check:\n",
    "#   1. All three sides are positive (> 0). Use a single assert for all three.\n",
    "#   2. Each side is less than the sum of the other two (triangle inequality).\n",
    "#   Each assert should include a descriptive message.\n",
    "#   Test:\n",
    "#     validate_triangle(3, 4, 5)  → passes silently\n",
    "#     validate_triangle(0, 4, 5)  → AssertionError (side not positive)\n",
    "#     validate_triangle(1, 2, 10) → AssertionError (violates triangle inequality)\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "3f6ba317-92ce-428f-808a-847f74939312",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.558147Z",
     "iopub.status.busy": "2026-09-25T18:45:29.557653Z",
     "iopub.status.idle": "2026-09-25T18:45:29.562505Z",
     "shell.execute_reply": "2026-09-25T18:45:29.561791Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3, 4, 5) is a valid triangle\n",
      "AssertionError: All sides must be positive\n",
      "AssertionError: Side c=10 violates the triangle inequality\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "def validate_triangle(a, b, c):\n",
    "    assert a > 0 and b > 0 and c > 0, \"All sides must be positive\"\n",
    "    assert a < b + c, f\"Side a={a} violates the triangle inequality\"\n",
    "    assert b < a + c, f\"Side b={b} violates the triangle inequality\"\n",
    "    assert c < a + b, f\"Side c={c} violates the triangle inequality\"\n",
    "\n",
    "validate_triangle(3, 4, 5)   # passes silently\n",
    "print(\"(3, 4, 5) is a valid triangle\")\n",
    "\n",
    "try:\n",
    "    validate_triangle(0, 4, 5)\n",
    "except AssertionError as e:\n",
    "    print(f\"AssertionError: {e}\")\n",
    "\n",
    "try:\n",
    "    validate_triangle(1, 2, 10)\n",
    "except AssertionError as e:\n",
    "    print(f\"AssertionError: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89d2c31e",
   "metadata": {},
   "source": [
    "### Systematic Bisection\n",
    "\n",
    "When a bug is hard to pin down, divide and conquer. Bisection debugging works like this: when a multi-step function produces the wrong answer and you don't know which step is at fault, add a checkpoint halfway through and check whether the intermediate data is already wrong at that point. If it is, the bug is in the first half; if not, it's in the second half. Keep halving until you isolate the exact line. This is much faster than reading every line from top to bottom.\n",
    "\n",
    "The example below has a three-stage pipeline with a real bug. The bisection steps show how to narrow it down without reading every line."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-89d2c31e",
   "metadata": {},
   "source": [
    "```{index} bisection debugging\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "a0a46a01",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.564173Z",
     "iopub.status.busy": "2026-09-25T18:45:29.563670Z",
     "iopub.status.idle": "2026-09-25T18:45:29.570213Z",
     "shell.execute_reply": "2026-09-25T18:45:29.569428Z"
    }
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Result:   10.4\n",
      "Expected: 13.0\n",
      "\n",
      "DEBUG midpoint: celsius  = [0.0, 100.0, 37.0, 25.0, -10.0]\n",
      "DEBUG midpoint: filtered = [0.0, 37.0, 25.0, -10.0]\n",
      "\n",
      "DEBUG Stage 3: sum = 52.0, dividing by len(celsius) = 5\n",
      "Bug found: 'len(celsius)' should be 'len(filtered)'\n",
      "\n",
      "Fixed result: 13.0\n"
     ]
    }
   ],
   "source": [
    "def analyze_temperatures(readings):\n",
    "    \"\"\"\n",
    "    Convert Fahrenheit readings to Celsius, discard outliers\n",
    "    (below -10 °C or above 45 °C), then return the average.\n",
    "    For [32, 212, 98.6, 77, 14] the result should be 13.0.\n",
    "    \"\"\"\n",
    "    # Stage 1: convert to Celsius\n",
    "    celsius = []\n",
    "    for f in readings:\n",
    "        celsius.append((f - 32) * 5 / 9)\n",
    "\n",
    "    # Stage 2: filter outliers\n",
    "    filtered = []\n",
    "    for t in celsius:\n",
    "        if -10 <= t <= 45:\n",
    "            filtered.append(t)\n",
    "\n",
    "    # Stage 3: compute average  ← bug is here\n",
    "    average = sum(filtered) / len(celsius)   # wrong: divides by original length\n",
    "    return average\n",
    "\n",
    "\n",
    "readings = [32, 212, 98.6, 77, 14]\n",
    "print(f\"Result:   {analyze_temperatures(readings):.1f}\")  # prints 10.4\n",
    "print(f\"Expected: 13.0\")\n",
    "\n",
    "# --- Bisection step 1: checkpoint after Stage 2 (the midpoint of three stages) ---\n",
    "celsius = []\n",
    "for f in readings:\n",
    "    celsius.append((f - 32) * 5 / 9)\n",
    "filtered = []\n",
    "for t in celsius:\n",
    "    if -10 <= t <= 45:\n",
    "        filtered.append(t)\n",
    "print(f\"\\nDEBUG midpoint: celsius  = {celsius}\")\n",
    "print(f\"DEBUG midpoint: filtered = {filtered}\")\n",
    "# celsius  = [0.0, 100.0, 37.0, 25.0, -10.0]\n",
    "# filtered = [0.0, 37.0, 25.0, -10.0]   ← correct (100.0 filtered out, 4 values remain)\n",
    "# Stages 1 and 2 are fine; the bug must be in Stage 3.\n",
    "\n",
    "# --- Bisection step 2: inspect Stage 3 ---\n",
    "print(f\"\\nDEBUG Stage 3: sum = {sum(filtered):.1f}, dividing by len(celsius) = {len(celsius)}\")\n",
    "# sum = 52.0, dividing by 5  ← wrong! should be len(filtered) = 4\n",
    "print(\"Bug found: 'len(celsius)' should be 'len(filtered)'\\n\")\n",
    "\n",
    "# --- Fix ---\n",
    "average = sum(filtered) / len(filtered)\n",
    "print(f\"Fixed result: {average:.1f}\")   # 13.0\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f130d68a",
   "metadata": {},
   "source": [
    "## Logging\n",
    "\n",
    "```{index} logging module\n",
    "```\n",
    "\n",
    "Print-statement debugging works, but the `print()` calls have to be deleted when you are done, and they cannot be turned on again later. The `logging` module solves this. It provides a flexible framework for recording diagnostic messages during program execution: you control *which* messages appear, *where* they go, and *how much detail* to include, without changing your code.\n",
    "\n",
    "### Log Levels\n",
    "\n",
    "```{index} log level, logging.basicConfig()\n",
    "```\n",
    "\n",
    "| Level | Value | When to use |\n",
    "|---|---|---|\n",
    "| `DEBUG` | 10 | Detailed diagnostic info (development only) |\n",
    "| `INFO` | 20 | Confirmation that things are working as expected |\n",
    "| `WARNING` | 30 | Something unexpected; program still running |\n",
    "| `ERROR` | 40 | A more serious problem; something failed |\n",
    "| `CRITICAL` | 50 | A severe error; program may not continue |\n",
    "\n",
    "The default level is `WARNING`: only `WARNING`, `ERROR`, and `CRITICAL` messages appear unless you configure a lower threshold."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb9b991b",
   "metadata": {},
   "source": [
    "When configuring logging, you will usually want to save the logs to a file. You can do this in `logging.basicConfig()` with the `filename=` parameter.\n",
    "\n",
    "> **Note: `basicConfig()` in notebooks.** `logging.basicConfig()` is a *no-op* (short for \"no operation\") after the first call in a session: if the root logger already has handlers attached, the call is silently ignored. In a notebook, where all cells share the same kernel state, only the first `basicConfig()` call takes effect. The code cells below pass `force=True` to `basicConfig()`, which removes and closes any existing handlers before applying the new configuration, so each cell behaves correctly regardless of run order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "782e3fec",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.572047Z",
     "iopub.status.busy": "2026-09-25T18:45:29.571330Z",
     "iopub.status.idle": "2026-09-25T18:45:29.575422Z",
     "shell.execute_reply": "2026-09-25T18:45:29.574674Z"
    }
   },
   "outputs": [],
   "source": [
    "import logging\n",
    "\n",
    "# Configure logging to save to a file\n",
    "# force=True removes and closes any existing handlers so this cell works on re-runs\n",
    "logging.basicConfig(filename='app.log', level=logging.INFO,\n",
    "                    format='%(asctime)s - %(levelname)s - %(message)s',\n",
    "                    force=True)\n",
    "\n",
    "logging.info(\"This is an info message saved to app.log\")\n",
    "logging.warning(\"This is a warning message\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "616ee712",
   "metadata": {},
   "source": [
    "Because this configuration writes only to `app.log`, nothing appears below the cell. To see log messages in both the console and the file, give `basicConfig()` two handlers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f5a16063",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.576784Z",
     "iopub.status.busy": "2026-09-25T18:45:29.576642Z",
     "iopub.status.idle": "2026-09-25T18:45:29.581002Z",
     "shell.execute_reply": "2026-09-25T18:45:29.580211Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2026-09-25 18:45:29,577 - INFO - This message will go to both the file and the console.\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "\n",
    "# Define the handlers\n",
    "file_handler = logging.FileHandler('app.log')\n",
    "console_handler = logging.StreamHandler()\n",
    "\n",
    "# Configure the root logger\n",
    "# force=True closes and removes any existing handlers before applying this configuration\n",
    "logging.basicConfig(\n",
    "    level=logging.INFO,\n",
    "    format='%(asctime)s - %(levelname)s - %(message)s',\n",
    "    handlers=[file_handler, console_handler],\n",
    "    force=True\n",
    ")\n",
    "\n",
    "logging.info(\"This message will go to both the file and the console.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fcfa4a75",
   "metadata": {},
   "source": [
    "With the level set to `DEBUG`, messages at every level are shown:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "51a369a5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.582588Z",
     "iopub.status.busy": "2026-09-25T18:45:29.582066Z",
     "iopub.status.idle": "2026-09-25T18:45:29.589758Z",
     "shell.execute_reply": "2026-09-25T18:45:29.589012Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG: Reading config file\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO: Server started on port 8080\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Disk space is low\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR: Failed to connect to database\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "CRITICAL: System is shutting down\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "\n",
    "# Show ALL levels (DEBUG and above)\n",
    "logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(message)s', force=True)\n",
    "\n",
    "logging.debug('Reading config file')        # detailed diagnostics\n",
    "logging.info('Server started on port 8080') # normal operations\n",
    "logging.warning('Disk space is low')        # something unexpected\n",
    "logging.error('Failed to connect to database')  # something failed\n",
    "logging.critical('System is shutting down') # severe error\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79d0d238",
   "metadata": {},
   "source": [
    "### Logging vs `print()`\n",
    "\n",
    "| | `print()` | `logging` |\n",
    "|---|---|---|\n",
    "| Severity levels | No | Yes |\n",
    "| Easy to silence | No (must delete/comment) | Yes (set level higher) |\n",
    "| Timestamps | No | Yes (with format string) |\n",
    "| Write to file | No | Yes |\n",
    "| Production-ready | No | Yes |\n",
    "\n",
    "Best practice: use `print()` for user-facing output and `logging` for diagnostic messages during development and production monitoring. Here is the division example from {ref}`Raising Exceptions <ch05-raising-exceptions>`, instrumented with logging instead of `print()`:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-79d0d238",
   "metadata": {},
   "source": [
    "```{index} logging module, print debugging\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "f035aa80",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.591372Z",
     "iopub.status.busy": "2026-09-25T18:45:29.590899Z",
     "iopub.status.idle": "2026-09-25T18:45:29.597182Z",
     "shell.execute_reply": "2026-09-25T18:45:29.596449Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG: divide_with_logging called with a=10, b=2\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO: Result: 5.0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5.0\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "\n",
    "logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(message)s', force=True)\n",
    "\n",
    "def divide_with_logging(a, b):\n",
    "    logging.debug(f'divide_with_logging called with a={a}, b={b}')\n",
    "    if b == 0:\n",
    "        logging.error('Division by zero attempted')\n",
    "        raise ValueError('Cannot divide by zero')\n",
    "    result = a / b\n",
    "    logging.info(f'Result: {result}')\n",
    "    return result\n",
    "\n",
    "print(divide_with_logging(10, 2))   # 5.0\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "ae51e116",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.598879Z",
     "iopub.status.busy": "2026-09-25T18:45:29.598360Z",
     "iopub.status.idle": "2026-09-25T18:45:29.601456Z",
     "shell.execute_reply": "2026-09-25T18:45:29.600725Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Add Logging\n",
    "#   Write `safe_sqrt(x)` that uses `logging` instead of `print`:\n",
    "#     - DEBUG: log the input value before computing ('safe_sqrt called with x={x}')\n",
    "#     - WARNING: log a warning if x is negative\n",
    "#     - ERROR: raise ValueError if x is negative\n",
    "#     - INFO: log the result before returning\n",
    "#   Test: safe_sqrt(25) → 5.0; safe_sqrt(0) → 0.0; safe_sqrt(-4) → ValueError.\n",
    "import math\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "a1b2c3d4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-25T18:45:29.603185Z",
     "iopub.status.busy": "2026-09-25T18:45:29.602649Z",
     "iopub.status.idle": "2026-09-25T18:45:29.613987Z",
     "shell.execute_reply": "2026-09-25T18:45:29.613227Z"
    },
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG: safe_sqrt called with x=25\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO: Result: 5.0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5.0\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG: safe_sqrt called with x=0\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO: Result: 0.0\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG: safe_sqrt called with x=-4\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Negative input: -4\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR: Cannot take square root of a negative number\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0\n",
      "Caught: Cannot take square root of negative number: -4\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "import math\n",
    "import logging\n",
    "\n",
    "logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(message)s', force=True)\n",
    "\n",
    "def safe_sqrt(x):\n",
    "    logging.debug(f'safe_sqrt called with x={x}')\n",
    "    if x < 0:\n",
    "        logging.warning(f'Negative input: {x}')\n",
    "        logging.error('Cannot take square root of a negative number')\n",
    "        raise ValueError(f'Cannot take square root of negative number: {x}')\n",
    "    result = math.sqrt(x)\n",
    "    logging.info(f'Result: {result}')\n",
    "    return result\n",
    "\n",
    "print(safe_sqrt(25))   # 5.0\n",
    "print(safe_sqrt(0))    # 0.0\n",
    "\n",
    "try:\n",
    "    safe_sqrt(-4)      # raises ValueError\n",
    "except ValueError as e:\n",
    "    print(f'Caught: {e}')\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
