{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## CS 200: Exceptions\n", "\n", "
\n", "\n", "
\n", " \n", "### Video:\n", " \n", "See Exceptions\n", " \n", "### Exceptions: EAFP vs LBYL\n", " \n", "EAFP: easier to ask for forgiveness than permission (Perl programming language, per Larry Wall. See quotes of Larry Wall).\n", " \n", "LBYL: look before you leap. Risk management philosophy at the heart of exceptions.\n", " \n", "Try to anticipate things that can go wrong and mitigate the consequences. See https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python. Note: good exam question.\n", " \n", "### Risk Management\n", " \n", "Things can go wrong. Hope for the best, but expect the worst. In the words of the 20th \n", "century philosopher, Mike Tyson, everyone has a plan until they get punched in the face.\n", " \n", "I spent years in finance as a risk manager. My job was to try to imagine things that could go wrong and take steps to mitigate, if not eliminate, those risks. Farmers sell their crops on future markets to hedge against price fluctuations. Airlines buy jet fuel on futures markets to hedge price risk. Multinational companies buy currency futures to hedge against foreign exchange risk. Farmers can also insure against bad weather, like drought. Homeowners buy insurance protecting them from fire, flood, theft, and vandalism. Some companies (but not many) had business interruption insurance that protected them against the covid-19 pandemic shutting down their business.\n", " \n", "In each of the cases, there is a foreseeable, but uncertain, adverse event:\n", "- fluctuations in crop prices, fuel prices, and foreign exchange rates.\n", "- the weather\n", "- fire, flood, theft, and vandalism\n", "- a global pandemic\n", " \n", "Investors can hedge their stock market investments using options. A call option pays off if the price of a stock goes up. A put option pays off if the price of a stock goes down. Many investors use combinations of options to protect their portfolios from uncertain future events.\n", " \n", "In the words of another twentieth century philosopher, Yogi Berra, it is difficult to make predictions, especially about the future.\n", " " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The Zen of Python, by Tim Peters\n", "\n", "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n", "Complex is better than complicated.\n", "Flat is better than nested.\n", "Sparse is better than dense.\n", "Readability counts.\n", "Special cases aren't special enough to break the rules.\n", "Although practicality beats purity.\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "In the face of ambiguity, refuse the temptation to guess.\n", "There should be one-- and preferably only one --obvious way to do it.\n", "Although that way may not be obvious at first unless you're Dutch.\n", "Now is better than never.\n", "Although never is often better than *right* now.\n", "If the implementation is hard to explain, it's a bad idea.\n", "If the implementation is easy to explain, it may be a good idea.\n", "Namespaces are one honking great idea -- let's do more of those!\n" ] } ], "source": [ "import this" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reading\n", "\n", "- Python Cookbook, chapter 14: Testing, Debugging, and Exceptions\n", "- Learning Python, chapters 33 - 36\n", "- exceptions.py\n", "\n", "\n", "List of built-in exceptions\n", "\n", "
\n", "BaseException\n", " +-- SystemExit\n", " +-- KeyboardInterrupt\n", " +-- GeneratorExit\n", " +-- Exception\n", " +-- StopIteration\n", " +-- StopAsyncIteration\n", " +-- ArithmeticError\n", " | +-- FloatingPointError\n", " | +-- OverflowError\n", " | +-- ZeroDivisionError\n", " +-- AssertionError\n", " +-- AttributeError\n", " +-- BufferError\n", " +-- EOFError\n", " +-- ImportError\n", " +-- LookupError\n", " | +-- IndexError\n", " | +-- KeyError\n", " +-- MemoryError\n", " +-- NameError\n", " | +-- UnboundLocalError\n", " +-- OSError\n", " | +-- BlockingIOError\n", " | +-- ChildProcessError\n", " | +-- ConnectionError\n", " | | +-- BrokenPipeError\n", " | | +-- ConnectionAbortedError\n", " | | +-- ConnectionRefusedError\n", " | | +-- ConnectionResetError\n", " | +-- FileExistsError\n", " | +-- FileNotFoundError\n", " | +-- InterruptedError\n", " | +-- IsADirectoryError\n", " | +-- NotADirectoryError\n", " | +-- PermissionError\n", " | +-- ProcessLookupError\n", " | +-- TimeoutError\n", " +-- ReferenceError\n", " +-- RuntimeError\n", " | +-- NotImplementedError\n", " | +-- RecursionError\n", " +-- SyntaxError\n", " | +-- IndentationError\n", " | +-- TabError\n", " +-- SystemError\n", " +-- TypeError\n", " +-- ValueError\n", " | +-- UnicodeError\n", " | +-- UnicodeDecodeError\n", " | +-- UnicodeEncodeError\n", " | +-- UnicodeTranslateError\n", " +-- Warning\n", " +-- DeprecationWarning\n", " +-- PendingDeprecationWarning\n", " +-- RuntimeWarning\n", " +-- SyntaxWarning\n", " +-- UserWarning\n", " +-- FutureWarning\n", " +-- ImportWarning\n", " +-- UnicodeWarning\n", " +-- BytesWarning\n", " +-- ResourceWarning\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ZeroDivisionError: division by zero" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def f1():\n", " return 1/0" ] }, { "cell_type": "code", "execution_count": 3, "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[0;32m/tmp/ipykernel_3588831/2719331641.py\u001b[0m in \u001b[0;36m
assert()
function can be used to monitor the execution of the program. At any point, the programmer can assert statements that should be true. If the statement is not true, assert will raise an exception.\n",
"\n",
"Below we assert that the input parameter, x, is even."
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [],
"source": [
"def f20(x):\n",
" assert(x % 2 == 0)"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [],
"source": [
"f20(2)"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [
{
"ename": "AssertionError",
"evalue": "",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m