{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exceptions and Assertions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Jupyter notebooks\n",
    "\n",
    "This is a space where text and code come together to form a coherent document. Throughout the course, we will make use of Jupyter notebooks for illustration purposes and for experimentation. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Motivation\n",
    "Encountering errors is a natural part of programming (happens more often for beginners). Reading and understanding source of errors is crucial for successful implementation of an idea:\n",
    "    - Reading error messages help us grasp coding rules\n",
    "    - Understanding error messages helps avoid bad or unexpected behavior in code"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exceptions\n",
    "Python exceptions occur whenever the interpreter cannot execute a line of code. We have seen many kind of exceptions so far, such as `TypeError`, `NameError`, and `ValueError` exceptions. It is normal to encounter errors while programming, but a programmer should write code that handles exceptions well in case they occur. Handling exceptions makes sure that the program does not crash in unfamiliar cases."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The `try-except` structure\n",
    "The `try-except` structure allows handling specific or general exceptions when they occur. Let's examine an example that might result in an exception:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Enter an integer: 10\n",
      "Enter an integer: 0\n"
     ]
    },
    {
     "output_type": "error",
     "ename": "ZeroDivisionError",
     "evalue": "division by zero",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mZeroDivisionError\u001b[39m                         Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[1]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[32m      1\u001b[39m x = int(input(\u001b[33m\"Enter an integer: \"\u001b[39m))\n\u001b[32m      2\u001b[39m y = int(input(\u001b[33m\"Enter an integer: \"\u001b[39m))\n\u001b[32m      3\u001b[39m \n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m z = x/y\n\u001b[32m      5\u001b[39m print(z)\n",
      "\u001b[31mZeroDivisionError\u001b[39m: division by zero"
     ]
    }
   ],
   "source": [
    "x = int(input(\"Enter an integer: \"))\n",
    "y = int(input(\"Enter an integer: \"))\n",
    "\n",
    "z = x/y\n",
    "print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, we might get either:\n",
    "- `ZeroDivisionError` : if y == 0.\n",
    "- `ValueError`: if user enters non-integer values.\n",
    "\n",
    "The `try-except` structure allows to handle previous errors by:\n",
    "- Placing our code inside a `try` block\n",
    "- Writing `except` blocks for each expected error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Enter an integer: 10\n",
      "Enter an integer: 0\n",
      "Cannot divide by 0!\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    x = int(input(\"Enter an integer: \"))\n",
    "    y = int(input(\"Enter an integer: \"))\n",
    "\n",
    "    z = x/y\n",
    "    print(z)\n",
    "\n",
    "except ZeroDivisionError:\n",
    "    print(\"Cannot divide by 0!\")\n",
    "except ValueError:\n",
    "    print(\"Bad input! Please enter integers.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition, we can avoid writing `except` blocks for each error if we want to handle all errors at once. We do so by writing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Enter an integer: 10\n",
      "Enter an integer: abc\n",
      "Bad Input!\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    x = int(input(\"Enter an integer: \"))\n",
    "    y = int(input(\"Enter an integer: \"))\n",
    "\n",
    "    z = x/y\n",
    "    print(z)\n",
    "\n",
    "except:\n",
    "    print(\"Bad Input!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here, the `except` block handles all types of exceptions but prints the same message. Hence there is a tradeoff between lines of code written and detail of the display message."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Optional clauses in `try-except`\n",
    "We can end a `try-except` block with an optional `else` clause, the statemens under which get executed **only if no exceptions occurs**. This optional `else` clause is placed after all `except` clauses. Example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Enter an integer: 10\n",
      "Enter an integer: 4\n",
      "2.5\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    x = int(input(\"Enter an integer: \"))\n",
    "    y = int(input(\"Enter an integer: \"))\n",
    "    z = x/y\n",
    "except:\n",
    "    print(\"Bad Input!\")\n",
    "else:\n",
    "    print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can end a `try-except` block with an optional `finally` clause, the statemens under which **always get executed**, whether an exception is raised or not. This optional `finally` clause is placed after all `except` clauses. Example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Enter an integer: 10\n",
      "Enter an integer: 2\n",
      "5.0\n",
      "Original inputs: 10 2\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    a = input(\"Enter an integer: \")\n",
    "    x = int(a)\n",
    "    b = input(\"Enter an integer: \")\n",
    "    y = int(b)\n",
    "    \n",
    "    z = x/y\n",
    "except:\n",
    "    print(\"Bad Input!\")\n",
    "else:\n",
    "    print(z)\n",
    "finally:\n",
    "    print(\"Original inputs:\", a, b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Assertions\n",
    "In Python, we can raise an `AssertionError` to prevent code from further\n",
    "execution. For example, recall our user-defined `my_sqrt()` function: we need the code to stop if the function is given an invalid input for example. \n",
    "\n",
    "The syntax for raising an assertion is the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "error",
     "ename": "NameError",
     "evalue": "name 'boolean_condition' is not defined",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mNameError\u001b[39m                                 Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[6]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28;01massert\u001b[39;00m boolean_condition, \u001b[33m'Error message.'\u001b[39m\n",
      "\u001b[31mNameError\u001b[39m: name 'boolean_condition' is not defined"
     ]
    }
   ],
   "source": [
    "assert boolean_condition, 'Error message.'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `assert` statement will try to assert that `boolean_condition` is `True`. If not, it will display the message: 'Error message'. \n",
    "\n",
    "Let's try to implement an assertion in our user-defined square-root function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def my_sqrt(x, epsilon=1E-5):\n",
    "    assert (type(x) == int or type(x) == float) and x >=0, \"Bad input!\"\n",
    "    \n",
    "    # begin function definition\n",
    "    ..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above (truncated) function definition, an `assert` statement is placed before the code enters the rest of the function to verify that the input `x` is appropriate. The code will raise an `AssertionError: Bad input!` if the boolean condition before it is `False`. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can refine our assertions even further to check or more conditions, for example, if `epsilon` is also appropriate:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def my_sqrt(x, epsilon=1E-5):\n",
    "    condition_1 = (type(x) == int or type(x) == float) and x >=0\n",
    "    assert condition_1, \"Bad input x!\"\n",
    "    \n",
    "    condition_2 = type(epsilon) == float \n",
    "    assert condition_2, \"Error tolerance must be a float!\"\n",
    "    \n",
    "    condition_3 = 0 < epsilon and epsilon <= 0.1\n",
    "    assert condition_3, \"Error tolerance is not in interval ]0, 0.1]\"\n",
    "    \n",
    "    # begin function definition\n",
    "    ...\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above (truncated) function definition, three `assert` statements are placed before the code enters the rest of the function to verify that the inputs conform to what we need them to."
   ]
  }
 ],
 "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.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
