{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "12b02b53",
   "metadata": {},
   "source": [
    "<h2>Exceptions & Errors</h2>\n",
    "<hr>\n",
    "<h4>Basic types of exceptions and errors</h4>\n",
    "<br>When we write code we often get error messages, these can be of some different types\n",
    "<br>\n",
    "<img src=\"media/errortypes.png\" width=70%>\n",
    "<br>\n",
    "Lets look att some of these"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c913485b",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "unterminated string literal (detected at line 2) (2743400583.py, line 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  Cell \u001b[0;32mIn[1], line 2\u001b[0;36m\u001b[0m\n\u001b[0;31m    print(\"hello)\u001b[0m\n\u001b[0m          ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unterminated string literal (detected at line 2)\n"
     ]
    }
   ],
   "source": [
    "#Syntax Error\n",
    "print(\"hello)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "eee2b687",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'hello' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m/Users/randlerm2/Documents/UU och Campus/Undervisning UU/Kurser 23-24/23 Coding in Python /Lectures/L5/Exceptions and Errors.ipynb Cell 3\u001b[0m line \u001b[0;36m2\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W2sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39m#Name error\u001b[39;00m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W2sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39mprint\u001b[39m(hello)\n",
      "\u001b[0;31mNameError\u001b[0m: name 'hello' is not defined"
     ]
    }
   ],
   "source": [
    "#Name error\n",
    "print(hello)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9cd0226e",
   "metadata": {},
   "outputs": [
    {
     "ename": "ZeroDivisionError",
     "evalue": "division by zero",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mZeroDivisionError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m/Users/randlerm2/Documents/UU och Campus/Undervisning UU/Kurser 23-24/23 Coding in Python /Lectures/L5/Exceptions and Errors.ipynb Cell 4\u001b[0m line \u001b[0;36m2\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W3sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39m#Zero division\u001b[39;00m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W3sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39m1\u001b[39m\u001b[39m/\u001b[39m\u001b[39m0\u001b[39m)\n",
      "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero"
     ]
    }
   ],
   "source": [
    "#Zero division\n",
    "print(1/0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ff7bba7a",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "unsupported operand type(s) for +: 'int' and 'str'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m/Users/randlerm2/Documents/UU och Campus/Undervisning UU/Kurser 23-24/23 Coding in Python /Lectures/L5/Exceptions and Errors.ipynb Cell 5\u001b[0m line \u001b[0;36m2\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W4sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39m#Type error\u001b[39;00m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W4sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39m1\u001b[39m\u001b[39m+\u001b[39m\u001b[39m\"\u001b[39m\u001b[39m2\u001b[39m\u001b[39m\"\u001b[39m)\n",
      "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'"
     ]
    }
   ],
   "source": [
    "#Type error\n",
    "print(1+\"2\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "874c4879",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "could not convert string to float: 'hello'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m/Users/randlerm2/Documents/UU och Campus/Undervisning UU/Kurser 23-24/23 Coding in Python /Lectures/L5/Exceptions and Errors.ipynb Cell 6\u001b[0m line \u001b[0;36m2\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W5sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39m#Value error\u001b[39;00m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W5sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mfloat\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mhello\u001b[39m\u001b[39m\"\u001b[39m))\n",
      "\u001b[0;31mValueError\u001b[0m: could not convert string to float: 'hello'"
     ]
    }
   ],
   "source": [
    "#Value error\n",
    "print(float(\"hello\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9e940ee8",
   "metadata": {},
   "outputs": [
    {
     "ename": "IndexError",
     "evalue": "list index out of range",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mIndexError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m/Users/randlerm2/Documents/UU och Campus/Undervisning UU/Kurser 23-24/23 Coding in Python /Lectures/L5/Exceptions and Errors.ipynb Cell 7\u001b[0m line \u001b[0;36m3\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W6sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39m#Index error\u001b[39;00m\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W6sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m list1 \u001b[39m=\u001b[39m [\u001b[39m1\u001b[39m,\u001b[39m2\u001b[39m,\u001b[39m3\u001b[39m,\u001b[39m4\u001b[39m,\u001b[39m5\u001b[39m]\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#W6sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mprint\u001b[39m(list1[\u001b[39m5\u001b[39m])\n",
      "\u001b[0;31mIndexError\u001b[0m: list index out of range"
     ]
    }
   ],
   "source": [
    "#Index error\n",
    "list1 = [1,2,3,4,5]\n",
    "print(list1[5])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecc8b0be",
   "metadata": {},
   "source": [
    "Sometimes we don't get any error message until we run the code - <b>runtime errors</b>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4d26e723",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "invalid literal for int() with base 10: 'fhfhg'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m/Users/randlerm2/Documents/UU och Campus/Undervisning UU/Kurser 23-24/23 Coding in Python /Lectures/L5/Exceptions and Errors.ipynb Cell 9\u001b[0m line \u001b[0;36m3\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X11sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39m#Try this but give \"five\" as input instead of an integer\u001b[39;00m\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X11sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m \u001b[39m#This will give a runtime ValueError\u001b[39;00m\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X11sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m x \u001b[39m=\u001b[39m \u001b[39mint\u001b[39m(\u001b[39minput\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mWhat\u001b[39m\u001b[39m'\u001b[39m\u001b[39ms x? \u001b[39m\u001b[39m\"\u001b[39m))\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X11sZmlsZQ%3D%3D?line=3'>4</a>\u001b[0m \u001b[39mprint\u001b[39m(\u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mx is \u001b[39m\u001b[39m{\u001b[39;00mx\u001b[39m}\u001b[39;00m\u001b[39m\"\u001b[39m)\n",
      "\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: 'fhfhg'"
     ]
    }
   ],
   "source": [
    "#Try this but give \"five\" as input instead of an integer\n",
    "#This will give a runtime ValueError\n",
    "x = int(input(\"What's x? \"))\n",
    "print(f\"x is {x}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c15b5de",
   "metadata": {},
   "source": [
    "<h4>Handling exceptions</h4>\n",
    "Lets try dealing with this kind of error in order for our code to handle them gracefully"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d93e851c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Standard code snippet for getting a number as an input using try-except-else\n",
    "while True:\n",
    "    try:\n",
    "        x = int(input(\"Please enter a number: \"))\n",
    "    except ValueError:\n",
    "        print(\"Oops!  That was no valid number.  Try again...\")\n",
    "    else:\n",
    "        break\n",
    "print(f\"The integer is: {x} \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "122712ba",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Oops!  That was no valid integer.  Try again...\n",
      "The integer is: 3 \n"
     ]
    }
   ],
   "source": [
    "#A slightly shorter version skipping else\n",
    "while True:\n",
    "    try:\n",
    "        x = int(input(\"Please enter a integer: \"))\n",
    "        break\n",
    "    except ValueError:\n",
    "        print(\"Oops!  That was no valid integer.  Try again...\")\n",
    "print(f\"The integer is: {x} \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3877e062",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The integer is: 5 \n"
     ]
    }
   ],
   "source": [
    "#Version with no message, just asking again\n",
    "while True:\n",
    "    try:\n",
    "        x = int(input(\"Please enter a integer: \"))\n",
    "        break\n",
    "    except ValueError:\n",
    "        pass\n",
    "print(f\"The integer is: {x} \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34e5a0c2",
   "metadata": {},
   "source": [
    "Python will tell us what's wrong in the standard cases, but sometimes we might need a bit more control raising our own error messages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0cde0953",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Not an integer\n"
     ]
    },
    {
     "ename": "AssertionError",
     "evalue": "Not an even integer",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAssertionError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m/Users/randlerm2/Documents/UU och Campus/Undervisning UU/Kurser 23-24/23 Coding in Python /Lectures/L5/Exceptions and Errors.ipynb Cell 15\u001b[0m line \u001b[0;36m5\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X20sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m \u001b[39mtry\u001b[39;00m:\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X20sZmlsZQ%3D%3D?line=3'>4</a>\u001b[0m     x \u001b[39m=\u001b[39m \u001b[39mint\u001b[39m(\u001b[39minput\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mPlease enter an even integer: \u001b[39m\u001b[39m\"\u001b[39m))\n\u001b[0;32m----> <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X20sZmlsZQ%3D%3D?line=4'>5</a>\u001b[0m     \u001b[39massert\u001b[39;00m x\u001b[39m%\u001b[39m\u001b[39m2\u001b[39m \u001b[39m==\u001b[39m \u001b[39m0\u001b[39m, \u001b[39m\"\u001b[39m\u001b[39mNot an even integer\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X20sZmlsZQ%3D%3D?line=5'>6</a>\u001b[0m     \u001b[39mif\u001b[39;00m x\u001b[39m%\u001b[39m\u001b[39m2\u001b[39m:\n\u001b[1;32m      <a href='vscode-notebook-cell:/Users/randlerm2/Documents/UU%20och%20Campus/Undervisning%20UU/Kurser%2023-24/23%20Coding%20in%20Python%20/Lectures/L5/Exceptions%20and%20Errors.ipynb#X20sZmlsZQ%3D%3D?line=6'>7</a>\u001b[0m         \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m()\n",
      "\u001b[0;31mAssertionError\u001b[0m: Not an even integer"
     ]
    }
   ],
   "source": [
    "#Raising an Assertionerror message with \"assert\"\n",
    "while True:\n",
    "    try:\n",
    "        x = int(input(\"Please enter an even integer: \"))\n",
    "        assert x%2 == 0, \"Not an even integer\"\n",
    "        if x%2:\n",
    "            raise ValueError()\n",
    "        break\n",
    "    except ValueError:\n",
    "        #pass\n",
    "        if isinstance(x, int):\n",
    "            print(x)\n",
    "            print(\"Integer but not even\")\n",
    "            x = \"\"\n",
    "        else:\n",
    "            print(\"Not an integer\")\n",
    "print(f\"The even integer is: {x} \")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b8e04a2",
   "metadata": {},
   "source": [
    "<p>Going a bit forward we can create our own custom exception type</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3fe6b002",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Not an integer\n",
      "Not an even integer\n",
      "The even integer is: 6 \n"
     ]
    }
   ],
   "source": [
    "#Creating custom exception\n",
    "class NotEvenError(Exception):\n",
    "    pass\n",
    "#The actual code using the custom exception\n",
    "while True:\n",
    "    try:\n",
    "        x = int(input(\"Please enter an even integer: \"))\n",
    "        if x%2:\n",
    "            raise NotEvenError()\n",
    "        break\n",
    "    except ValueError:\n",
    "        print(\"Not an integer\")\n",
    "    except NotEvenError:\n",
    "        print(\"Not an even integer\")\n",
    "print(f\"The even integer is: {x} \")"
   ]
  }
 ],
 "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.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
