{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a name=top></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exceptions and Exception Handling"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This work is licensed under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/)\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "This unit addresses  the almost inevitable occurence of unanticipated errors in code, and methods to detect and handle *exceptions*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note:** This \"notebook plus modules\" organization is useful when the collection of function definitions usd in a project is lengthy, and would otherwise clutter up the notebook and hamper readability."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Handing and Raising Exceptions\n",
    "\n",
    "Ideally, when we write a computer program for a mathematical task, we will plan in advance for every possibility, and design an algorithm to handle all of them.\n",
    "For example, anticipating the possibility of division by zero and avoiding it is a common issue in making a program **robust**.\n",
    "\n",
    "However this is not always feasible; in particular while still developing a program, there might be situations that you have not yet anticipated, and so it can be useful to write a program that will detect problems that occur while the program is running, and handle them in a reasonable way.\n",
    "\n",
    "We start by considering a very basic code for our favorite example, solving quadratic equations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import sqrt  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def quadratic_roots(a, b, c):\n",
    "    root_of_discriminant = sqrt(b**2 - 4*a*c)\n",
    "    return ( (-b - root_of_discriminant)/(2*a),  (-b + root_of_discriminant)/(2*a) )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Let's solve the quadratic equation 2*x**2 + -10*x + 8 = 0\n",
      "The roots are 1 and 4\n"
     ]
    }
   ],
   "source": [
    "# An easy and familiar test case\n",
    "(a, b, c) = (2, -10, 8)\n",
    "print(\"Let's solve the quadratic equation %g*x**2 + %g*x + %g = 0\" % (a, b, c))\n",
    "(root0, root1) = quadratic_roots(a, b, c)\n",
    "print(\"The roots are %g and %g\" % (root0, root1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Try it repeatedly, with some \"destructive testing\": seek input choices that will cause various problems.\n",
    "\n",
    "For this, it is is useful to have an interactive loop to ask for test cases:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Testing: add some hard cases, interactively\n",
    "print(\"Let's solve some quadratic equations a*x**2 + b*x + c = 0\")\n",
    "keepgoing = True\n",
    "while keepgoing: \n",
    "    a = float(input(\"a = \"))\n",
    "    b = float(input(\"b = \"))\n",
    "    c = float(input(\"c = \"))\n",
    "    print(\"Solving the quadratic equation %g*x**2 + %g*x + %g = 0\" % (a, b, c))\n",
    "    (root0, root1) = quadratic_roots(a, b, c)\n",
    "    print(\"The roots are %g and %g\" % (root0, root1))\n",
    "    yesorno = input(\"Do you want to try another case? [Answer y/n]: \")\n",
    "    keepgoing = yesorno[0] in {'y','Y'}  # examine the first letter only!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let me know what problems you found; we will work on detecting and handling all of them."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some messages I get ended with these lines, whose meaning we will explore:\n",
    "\n",
    "- ZeroDivisionError: float division by zero\n",
    "- ValueError: math domain error\n",
    "- ValueError: could not convert string to float ..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Catching any \"exceptional\" situation and handling it specially\n",
    "\n",
    "Here is a minimal way to catch all problems, and at least apologize for failing to solve the equation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exception handling, version 1\n",
    "print(\"Let's solve some quadratic equations a*x**2 + b*x + c = 0\")\n",
    "keepgoing = True\n",
    "while keepgoing: \n",
    "    try:\n",
    "        a = float(input(\"a = \"))\n",
    "        b = float(input(\"b = \"))\n",
    "        c = float(input(\"c = \"))\n",
    "        print(\"Solving the quadratic equation %g*x**2 + %g*x + %g = 0\" % (a, b, c))\n",
    "        (root0, root1) = quadratic_roots(a, b, c)\n",
    "        print(\"The roots are %g and %g\" % (root0, root1))\n",
    "    except:\n",
    "        print(\"Something went wrong; sorry!\")\n",
    "    yesorno = input(\"Do you want to try another case? [Answer y/n]: \")\n",
    "    keepgoing = yesorno[0] in {'y','Y'}    # examine the first letter only, so \"nevermore\" means \"no\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## This try/except structure does two things:\n",
    "\n",
    "- it first *tries* to run the code in the (indented) block introduced by the colon after the statement `try`\n",
    "\n",
    "- if anything goes wrong (in Python jargon, if any **exception** occurs) it gives up on that `try` block and runs the code in the block under the statement `except`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Catching and displaying the exception error message\n",
    "\n",
    "One thing has been lost though: the messages like \"float division by zero\" as seen above, which say what sort of exception occured.\n",
    "\n",
    "We can regain some of that, by having <code>except</code> statement save that message into a variable:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exception handling, version 2: displaying the exception\n",
    "\n",
    "print(\"Let's solve some quadratic equations a*x**2 + b*x + c = 0\")\n",
    "keepgoing = True\n",
    "while keepgoing: \n",
    "    try:\n",
    "        a = float(input(\"a = \"))\n",
    "        b = float(input(\"b = \"))\n",
    "        c = float(input(\"c = \"))\n",
    "        print(\"Solving the quadratic equation %g*x**2 + %g*x + %g = 0\" % (a, b, c))\n",
    "        (root0, root1) = quadratic_roots(a, b, c)\n",
    "        print(\"The roots are %g and %g\" % (root0, root1))\n",
    "    except Exception as what_just_happened:\n",
    "        print(\"Something went wrong; sorry!\")\n",
    "        print(\"The exception is: \", what_just_happened)\n",
    "        print(\"The exception message is: \", what_just_happened.args[0])\n",
    "        #if what_just_happened == \"float division by zero\":\n",
    "        #if what_just_happened[:5] == \"float\":\n",
    "        #    print(\"You cannot divide by zero.\")\n",
    "    yesorno = input(\"Do you want to try another case? [Answer y/n]: \")\n",
    "    keepgoing = yesorno[0] in {'y','Y'}    # examine the first letter only, so \"nevermore\" means \"no\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This version detects  every possible exception and handles them all in the same way, whether it be a problem in arithmetic (like the dreaded division by zero) or the user making a typing error in the input of the coefficients. Try answering \"one\" when asked for a coefficient!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Handling specific exception types\n",
    "\n",
    "Python divides exceptions into many types, and the statement `except` can be given the name of an exception type, so that it then handles only that type of exception.\n",
    "\n",
    "For example, in the case of division be zero, where we originally got a message\n",
    "\n",
    "    ZeroDivisionError: float division by zero\n",
    "\n",
    "we can catch that particular exception and handle it specially:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exception handling, version 3: as above, but with special handing for division by zero.\n",
    "\n",
    "print(\"Let's solve some quadratic equations a*x**2 + b*x + c = 0\")\n",
    "keepgoing = True\n",
    "while keepgoing:\n",
    "    try:\n",
    "        a = float(input(\"a = \"))\n",
    "        b = float(input(\"b = \"))\n",
    "        c = float(input(\"c = \"))\n",
    "        print(\"Solving the quadratic equation %g*x**2 + %g*x + %g = 0\" % (a, b, c))\n",
    "        (root0, root1) = quadratic_roots(a, b, c)\n",
    "        print(\"The roots are %g and %g\" % (root0, root1))\n",
    "    except ZeroDivisionError as what_just_happened:  # Note the \"CamelCase\": capitalization of each word\n",
    "        print(\"Division by zero; the first coefficient cannot be zero!\")\n",
    "        print(\"Please try again.\")\n",
    "    yesorno = input(\"Do you want to try another case? [Answer y/n]: \")\n",
    "    keepgoing = yesorno[0] in {'y','Y'}  # examine the first letter only, so \"nevermore\" means \"no\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Handling multiple exception types\n",
    "\n",
    "However, this still crashes with other errors, lke typos in the input.\n",
    "To detect several types of exception, and handle each in an appropriate way, there can be a list of <code>except</code> statements, each with a block of code to run when that exception is detected.\n",
    "The type <code>Exception</code> was already seen above; it is just the totally generic case, so can be used as a catch-all after a list of exception types have been handled."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Experiment a bit, and you will see how these multiple `except` statements are used:\n",
    "- the first `except` clause that matches is used, and any later ones are ignored;\n",
    "- only if none matches does the code go back to simply \"crashing\", as with version 0 above."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary: a while-try-except pattern for interactive programs\n",
    "\n",
    "For programs with interactive input, a useful pattern for robustly handling errors or surprises in the input is a while-try-except pattern, with a form like:\n",
    "\n",
    "    try_again = True\n",
    "    while try_again:\n",
    "        try:\n",
    "            Get input\n",
    "            Do stuff with it\n",
    "            try_again = False\n",
    "        except Exception as message:\n",
    "            print(\"Exception\", message, \" occurred; please try again.\")\n",
    "            Maybe actually fix the problem, and if successful: try_again = False\n",
    "\n",
    "One can refine this by adding `except` clauses for as many specific exception types as are relevant, with more specific handling for each."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a name=Exercise-D-A></a>\n",
    "### Exercise D-A. Add handling for multiple types of exception\n",
    "\n",
    "Copy your latest version of a \"quadratic_solver\" function here into your module name something like \"`math246`\" created for Unit 9) — or into a new file named something like `quadratic_solvers.py`.\n",
    "Then augment that function with multiple `except` clauses to handle all exceptions that we can get to occur.\n",
    "\n",
    "First, read about the possibilities, for example in Section 5 of the official\n",
    "[Python 3 Standard Library Reference Manual](https://docs.python.org/3/library/)  \n",
    "at https://docs.python.org/3/library/exceptions.html, or other sources that you can find.\n",
    "\n",
    "Two exceptions of particular importance for us are `ValueError` and `ArithmeticError`, and sub-types of the latter like `ZeroDivisionError` and `OverflowError`.\n",
    "(Note the \"CamelCase\" capitalization of each word in an exception name:\n",
    "it is essential to get this right, since Python is case-sensitive.)\n",
    "\n",
    "Aside: If you find a source on Python exceptions that you prefer to the above references, please let us all know!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a name=Exercise-D-B></a>\n",
    "## Exercise D-B. Handling division by zero in Newton's method\n",
    "\n",
    "Using a basic code for Newton's Method (such as the one I provide in module `root_finders`) experiment with exception handling for the possibility of division by zero.\n",
    "\n",
    "(You could then do likewise with the Secant Method.)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
