{ "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\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/82817062.py\u001b[0m in \u001b[0;36mf1\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf1\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "f1()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### NameError: name 'a' is not defined" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def f2():\n", " return a" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'a' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/1603317987.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/1734449526.py\u001b[0m in \u001b[0;36mf2\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'a' is not defined" ] } ], "source": [ "f2()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### IndexError: list index out of range" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def f3():\n", " a = []\n", " return a[2]" ] }, { "cell_type": "code", "execution_count": 7, "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[0;32m/tmp/ipykernel_3588831/1694196295.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf3\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/1222251901.py\u001b[0m in \u001b[0;36mf3\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf3\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mIndexError\u001b[0m: list index out of range" ] } ], "source": [ "f3()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### NameError: name 'foo' is not defined" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "def f4():\n", " return foo()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'foo' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/1205670228.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf4\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/608990109.py\u001b[0m in \u001b[0;36mf4\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf4\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfoo\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'foo' is not defined" ] } ], "source": [ "f4()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### FileNotFoundError: [Errno 2] No such file or directory: 'foo'" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def f5():\n", " for x in open(\"foo\"):\n", " print (x)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "ename": "FileNotFoundError", "evalue": "[Errno 2] No such file or directory: 'foo'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/257402558.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf5\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/3319180516.py\u001b[0m in \u001b[0;36mf5\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf5\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"foo\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'foo'" ] } ], "source": [ "f5()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ImportError: No module named 'foo' (may appear as ModuleNotFoundError)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "def f6():\n", " import foo" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "ename": "ModuleNotFoundError", "evalue": "No module named 'foo'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/3151912711.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf6\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/334674352.py\u001b[0m in \u001b[0;36mf6\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf6\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mfoo\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'foo'" ] } ], "source": [ "f6()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### KeyError: 'key'" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "def f7():\n", " d = {}\n", " return d['key']" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "ename": "KeyError", "evalue": "'key'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/24191879.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf7\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/2890225209.py\u001b[0m in \u001b[0;36mf7\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf7\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0md\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'key'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mKeyError\u001b[0m: 'key'" ] } ], "source": [ "f7()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### PermissionError: [Errno 13] Permission denied: '/hello'" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "import os\n", "def f8():\n", " os.mkdir(\"/hello\")" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "ename": "PermissionError", "evalue": "[Errno 13] Permission denied: '/hello'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mPermissionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/993499914.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf8\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/2027675755.py\u001b[0m in \u001b[0;36mf8\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mos\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf8\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmkdir\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"/hello\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mPermissionError\u001b[0m: [Errno 13] Permission denied: '/hello'" ] } ], "source": [ "f8()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### RuntimeError: maximum recursion depth exceeded" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "import sys\n", "def f9():\n", " # print (sys.getrecursionlimit()) ==> 1000\n", " f9()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3000" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.getrecursionlimit()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "ename": "RecursionError", "evalue": "maximum recursion depth exceeded", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mRecursionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/1844206180.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf9\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/380940650.py\u001b[0m in \u001b[0;36mf9\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf9\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# print (sys.getrecursionlimit()) ==> 1000\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mf9\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "... last 1 frames repeated, from the frame below ...\n", "\u001b[0;32m/tmp/ipykernel_3588831/380940650.py\u001b[0m in \u001b[0;36mf9\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf9\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# print (sys.getrecursionlimit()) ==> 1000\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mf9\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mRecursionError\u001b[0m: maximum recursion depth exceeded" ] } ], "source": [ "f9()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### AttributeError: 'range' object has no attribute 'next'" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "def f10():\n", " g = range(5)\n", " g.next()" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'range' object has no attribute 'next'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/1690477009.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf10\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/1925680742.py\u001b[0m in \u001b[0;36mf10\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf10\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mg\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mg\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: 'range' object has no attribute 'next'" ] } ], "source": [ "f10()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### TypeError: 'range' object is not an iterator" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "def f11():\n", " g = range(5)\n", " next(g)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'range' object is not an iterator", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/1809916670.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf11\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/606302619.py\u001b[0m in \u001b[0;36mf11\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf11\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mg\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mg\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'range' object is not an iterator" ] } ], "source": [ "f11()" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "g = range(10)\n", "x = iter(g)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### StopIteration" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "def f12():\n", " g = (x for x in range(1))\n", " next(g)\n", " next(g)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/3161046385.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf12\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/3182897007.py\u001b[0m in \u001b[0;36mf12\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mg\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mx\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mg\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mnext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mg\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mStopIteration\u001b[0m: " ] } ], "source": [ "f12()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### UnboundLocalError: local variable 'x' referenced before assignment" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "x = 0\n", "def f13():\n", " x += 1\n", " return x" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "ename": "UnboundLocalError", "evalue": "local variable 'x' referenced before assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/1256359740.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf13\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/871710112.py\u001b[0m in \u001b[0;36mf13\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf13\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mx\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mUnboundLocalError\u001b[0m: local variable 'x' referenced before assignment" ] } ], "source": [ "f13()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### user defined exceptions" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "class MyError(Exception):\n", " def __init__(self, value):\n", " self.value = value\n", " def __str__(self):\n", " return repr(self.value)\n", "\n", "# exceptions.MyError: 'oops!'\n", "def f14():\n", " raise MyError(\"oops!\")" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "ename": "MyError", "evalue": "'oops!'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mMyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/529271966.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf14\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/842390987.py\u001b[0m in \u001b[0;36mf14\u001b[0;34m()\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;31m# exceptions.MyError: 'oops!'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf14\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mMyError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"oops!\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mMyError\u001b[0m: 'oops!'" ] } ], "source": [ "f14()" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "def f14a():\n", " raise Exception(\"oops!\")" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "ename": "Exception", "evalue": "oops!", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_3588831/413542817.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf14a\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_3588831/464713622.py\u001b[0m in \u001b[0;36mf14a\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf14a\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"oops!\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mException\u001b[0m: oops!" ] } ], "source": [ "f14a()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### TypeError: this is a mistake" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "def f15():\n", " raise TypeError(\"this is a mistake\")" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "this is a mistake", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf15\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mf15\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf15\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"this is a mistake\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: this is a mistake" ] } ], "source": [ "f15()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### handling exceptions with try / except" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "def f16():\n", " try:\n", " 1 / 0\n", " except:\n", " print (\"You raised an exception\")" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "You raised an exception\n" ] } ], "source": [ "f16()" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def f17(x, y):\n", " try:\n", " result = x / y\n", " except ZeroDivisionError:\n", " print(\"division by zero!\")\n", " except TypeError:\n", " print(\"Oops! wrong type!\")\n", " else:\n", " print(\"result is\", result)\n", " finally:\n", " print(\"executing finally clause\")" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "result is 2.0\n", "executing finally clause\n" ] } ], "source": [ "f17(2,1)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "division by zero!\n", "executing finally clause\n" ] } ], "source": [ "f17(1,0)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Oops! wrong type!\n", "executing finally clause\n" ] } ], "source": [ "f17('1','2')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "division by zero!\n", "executing finally clause\n" ] } ], "source": [ "f17(2,0)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "result is 4.0\n", "executing finally clause\n" ] } ], "source": [ "f17(8,2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Another try/except example

\n", "\n", "like counttags() in homework" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "## import urllib\n", "import urllib.request\n", "\n", "def f17b(url):\n", " try:\n", " ufile = urllib.request.urlopen(url)\n", " test = ufile.read()\n", " return len(test)\n", " except IOError:\n", " return ('problem reading url:' + url)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1112972" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f17b('http://www.cnn.com')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'problem reading url:http://badcnn.com'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f17b('http://badcnn.com')" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f17b('http://cnnnn.com')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### sys.exc_info() returns information about the state of execution" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "import sys\n", "def f18():\n", " try:\n", " 1/0\n", " except:\n", " e = sys.exc_info()[0]\n", " print ( \"Error: {}\".format(e))\n", " return sys.exc_info()" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error: \n" ] }, { "data": { "text/plain": [ "(ZeroDivisionError,\n", " ZeroDivisionError('division by zero'),\n", " )" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f18()" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "def f19(x):\n", " if isinstance(x,float):\n", " raise TypeError( \"Can't work with float and can't convert to int, either\" )\n", " else:\n", " return x" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(9.0,float)" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f19(1)" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "Can't work with float and can't convert to int, either", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf19\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1.0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mf19\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf19\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mfloat\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m \u001b[0;34m\"Can't work with float and can't convert to int, either\"\u001b[0m \u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: Can't work with float and can't convert to int, either" ] } ], "source": [ "f19(1.0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### f20(1) => AssertionError \n", "\n", "The 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\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mf20\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mf20\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mf20\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32massert\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0;36m2\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m: " ] } ], "source": [ "f20(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### errno module can translate error numbers" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [], "source": [ "import errno\n", "def f21(filename):\n", " try:\n", " f = open(filename)\n", " except OSError as e:\n", " print (e)\n", " if e.errno == errno.ENOENT:\n", " print (\"File not found\")\n", " elif e.errno == errno.EACCES:\n", " print (\"Permission denied\")\n", " return e\n", " else:\n", " print (\"No problem\")\n" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Errno 2] No such file or directory: 'filename'\n", "File not found\n" ] }, { "data": { "text/plain": [ "FileNotFoundError(2, 'No such file or directory')" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f21('filename')" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No problem\n" ] } ], "source": [ "f21(\"exceptions.py\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are lots of possible errors." ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['E2BIG',\n", " 'EACCES',\n", " 'EADDRINUSE',\n", " 'EADDRNOTAVAIL',\n", " 'EADV',\n", " 'EAFNOSUPPORT',\n", " 'EAGAIN',\n", " 'EALREADY',\n", " 'EBADE',\n", " 'EBADF',\n", " 'EBADFD',\n", " 'EBADMSG',\n", " 'EBADR',\n", " 'EBADRQC',\n", " 'EBADSLT',\n", " 'EBFONT',\n", " 'EBUSY',\n", " 'ECANCELED',\n", " 'ECHILD',\n", " 'ECHRNG',\n", " 'ECOMM',\n", " 'ECONNABORTED',\n", " 'ECONNREFUSED',\n", " 'ECONNRESET',\n", " 'EDEADLK',\n", " 'EDEADLOCK',\n", " 'EDESTADDRREQ',\n", " 'EDOM',\n", " 'EDOTDOT',\n", " 'EDQUOT',\n", " 'EEXIST',\n", " 'EFAULT',\n", " 'EFBIG',\n", " 'EHOSTDOWN',\n", " 'EHOSTUNREACH',\n", " 'EIDRM',\n", " 'EILSEQ',\n", " 'EINPROGRESS',\n", " 'EINTR',\n", " 'EINVAL',\n", " 'EIO',\n", " 'EISCONN',\n", " 'EISDIR',\n", " 'EISNAM',\n", " 'EKEYEXPIRED',\n", " 'EKEYREJECTED',\n", " 'EKEYREVOKED',\n", " 'EL2HLT',\n", " 'EL2NSYNC',\n", " 'EL3HLT',\n", " 'EL3RST',\n", " 'ELIBACC',\n", " 'ELIBBAD',\n", " 'ELIBEXEC',\n", " 'ELIBMAX',\n", " 'ELIBSCN',\n", " 'ELNRNG',\n", " 'ELOOP',\n", " 'EMEDIUMTYPE',\n", " 'EMFILE',\n", " 'EMLINK',\n", " 'EMSGSIZE',\n", " 'EMULTIHOP',\n", " 'ENAMETOOLONG',\n", " 'ENAVAIL',\n", " 'ENETDOWN',\n", " 'ENETRESET',\n", " 'ENETUNREACH',\n", " 'ENFILE',\n", " 'ENOANO',\n", " 'ENOBUFS',\n", " 'ENOCSI',\n", " 'ENODATA',\n", " 'ENODEV',\n", " 'ENOENT',\n", " 'ENOEXEC',\n", " 'ENOKEY',\n", " 'ENOLCK',\n", " 'ENOLINK',\n", " 'ENOMEDIUM',\n", " 'ENOMEM',\n", " 'ENOMSG',\n", " 'ENONET',\n", " 'ENOPKG',\n", " 'ENOPROTOOPT',\n", " 'ENOSPC',\n", " 'ENOSR',\n", " 'ENOSTR',\n", " 'ENOSYS',\n", " 'ENOTBLK',\n", " 'ENOTCONN',\n", " 'ENOTDIR',\n", " 'ENOTEMPTY',\n", " 'ENOTNAM',\n", " 'ENOTRECOVERABLE',\n", " 'ENOTSOCK',\n", " 'ENOTSUP',\n", " 'ENOTTY',\n", " 'ENOTUNIQ',\n", " 'ENXIO',\n", " 'EOPNOTSUPP',\n", " 'EOVERFLOW',\n", " 'EOWNERDEAD',\n", " 'EPERM',\n", " 'EPFNOSUPPORT',\n", " 'EPIPE',\n", " 'EPROTO',\n", " 'EPROTONOSUPPORT',\n", " 'EPROTOTYPE',\n", " 'ERANGE',\n", " 'EREMCHG',\n", " 'EREMOTE',\n", " 'EREMOTEIO',\n", " 'ERESTART',\n", " 'ERFKILL',\n", " 'EROFS',\n", " 'ESHUTDOWN',\n", " 'ESOCKTNOSUPPORT',\n", " 'ESPIPE',\n", " 'ESRCH',\n", " 'ESRMNT',\n", " 'ESTALE',\n", " 'ESTRPIPE',\n", " 'ETIME',\n", " 'ETIMEDOUT',\n", " 'ETOOMANYREFS',\n", " 'ETXTBSY',\n", " 'EUCLEAN',\n", " 'EUNATCH',\n", " 'EUSERS',\n", " 'EWOULDBLOCK',\n", " 'EXDEV',\n", " 'EXFULL',\n", " '__doc__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " 'errorcode']" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(errno)" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Errno 2] No such file or directory: 'zzz'\n", "File not found\n" ] } ], "source": [ "x = f21('zzz')" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "FileNotFoundError(2, 'No such file or directory')" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__cause__',\n", " '__class__',\n", " '__context__',\n", " '__delattr__',\n", " '__dict__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__le__',\n", " '__lt__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__setattr__',\n", " '__setstate__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " '__suppress_context__',\n", " '__traceback__',\n", " 'args',\n", " 'characters_written',\n", " 'errno',\n", " 'filename',\n", " 'filename2',\n", " 'strerror',\n", " 'with_traceback']" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(x)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'zzz'" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x.filename" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x.errno" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Decorator for Exception Handling\n", "\n", "The following three functions each handles a TypeError exception. See https://medium.com/swlh/handling-exceptions-in-python-a-cleaner-way-using-decorators-fae22aa0abec" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "def area_square(length):\n", " try:\n", " print(length**2)\n", " except TypeError:\n", " print(\"area_square only takes numbers as the argument\")\n", "\n", "def area_circle(radius):\n", " try:\n", " print(3.142 * radius**2)\n", " except TypeError:\n", " print(\"area_circle only takes numbers as the argument\")\n", "\n", "def area_rectangle(length, breadth):\n", " try:\n", " print(length * breadth)\n", " except TypeError:\n", " print(\"area_rectangle only takes numbers as the argument\")" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "25\n", "area_square only takes numbers as the argument\n" ] } ], "source": [ "area_square(5)\n", "area_square([5])" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "78.55\n", "area_circle only takes numbers as the argument\n" ] } ], "source": [ "area_circle(5)\n", "area_circle('five')" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n", "area_rectangle only takes numbers as the argument\n" ] } ], "source": [ "area_rectangle(4,5)\n", "area_rectangle('four','five')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can define a decorator and apply it to each function." ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "def exception_handler(func):\n", " def inner_function(*args, **kwargs):\n", " try:\n", " func(*args, **kwargs)\n", " except TypeError:\n", " print(f\"{func.__name__} only takes numbers as the argument\")\n", " return inner_function\n", "\n", "@exception_handler\n", "def area_square(length):\n", " print(length * length)\n", "\n", "@exception_handler\n", "def area_circle(radius):\n", " print(3.14 * radius * radius)\n", "\n", "@exception_handler\n", "def area_rectangle(length, breadth):\n", " print(length * breadth)" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "12.56\n", "8\n", "area_square only takes numbers as the argument\n", "area_circle only takes numbers as the argument\n", "area_rectangle only takes numbers as the argument\n" ] } ], "source": [ "area_square(2)\n", "area_circle(2)\n", "area_rectangle(2, 4)\n", "area_square(\"some_str\")\n", "area_circle(\"some_other_str\")\n", "area_rectangle(\"some_other_rectangle\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Logging Exceptions\n", "\n", "See https://www.blog.pythonlibrary.org/2016/06/09/python-how-to-create-an-exception-logging-decorator/\n", "\n", "The logging module provides a uniform process for logging code events. See https://docs.python.org/3/howto/logging.html\n", "\n", "Here is an example." ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "import logging\n", "def create_logger():\n", " \"\"\"\n", " Creates a logging object and returns it\n", " \"\"\"\n", " logger = logging.getLogger(\"example_logger\")\n", " logger.setLevel(logging.INFO)\n", " # create the logging file handler\n", " fh = logging.FileHandler(\"/tmp/test.log1\")\n", " fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n", " formatter = logging.Formatter(fmt)\n", " fh.setFormatter(formatter)\n", " # add handler to logger object\n", " logger.addHandler(fh)\n", " return logger" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "logger = create_logger()" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__delattr__',\n", " '__dict__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__le__',\n", " '__lt__',\n", " '__module__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " '__weakref__',\n", " '_cache',\n", " '_log',\n", " 'addFilter',\n", " 'addHandler',\n", " 'callHandlers',\n", " 'critical',\n", " 'debug',\n", " 'disabled',\n", " 'error',\n", " 'exception',\n", " 'fatal',\n", " 'filter',\n", " 'filters',\n", " 'findCaller',\n", " 'getChild',\n", " 'getEffectiveLevel',\n", " 'handle',\n", " 'handlers',\n", " 'hasHandlers',\n", " 'info',\n", " 'isEnabledFor',\n", " 'level',\n", " 'log',\n", " 'makeRecord',\n", " 'manager',\n", " 'name',\n", " 'parent',\n", " 'propagate',\n", " 'removeFilter',\n", " 'removeHandler',\n", " 'root',\n", " 'setLevel',\n", " 'warn',\n", " 'warning']" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(logger)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "logger.info('This is info')\n", "logger.warning('this is a warning')\n", "logger.exception('this is an exception')" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "import subprocess\n", "(status, output) = subprocess.getstatusoutput('cat /tmp/test.log1')" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2020-10-21 10:57:21,331 - example_logger - INFO - This is info\n", "2020-10-21 10:57:21,331 - example_logger - WARNING - this is a warning\n", "2020-10-21 10:57:21,331 - example_logger - ERROR - this is an exception\n", "NoneType: None\n" ] } ], "source": [ "print (output)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create a decorator to log exceptions" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "import functools\n", "\n", "def exception(function):\n", " \"\"\"\n", " A decorator that wraps the passed in function and logs \n", " exceptions should one occur\n", " \"\"\"\n", " @functools.wraps(function)\n", " def wrapper(*args, **kwargs):\n", " logger = create_logger()\n", " try:\n", " return function(*args, **kwargs)\n", " except:\n", " # log the exception\n", " err = \"There was an exception in \"\n", " err += function.__name__\n", " logger.exception(err)\n", " # re-raise the exception\n", " raise\n", " return wrapper" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [], "source": [ "@exception\n", "def zero_divide():\n", " 1 / 0" ] }, { "cell_type": "code", "execution_count": 55, "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\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mzero_divide\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mwrapper\u001b[0;34m(*args, **kwargs)\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0mlogger\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcreate_logger\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mfunction\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 13\u001b[0m \u001b[0;32mexcept\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[0;31m# log the exception\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m\u001b[0m in \u001b[0;36mzero_divide\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;34m@\u001b[0m\u001b[0mexception\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mzero_divide\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;36m1\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "zero_divide()" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [], "source": [ "(status, output) = subprocess.getstatusoutput('cat /tmp/test.log1')" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2020-10-21 10:57:21,331 - example_logger - INFO - This is info\n", "2020-10-21 10:57:21,331 - example_logger - WARNING - this is a warning\n", "2020-10-21 10:57:21,331 - example_logger - ERROR - this is an exception\n", "NoneType: None\n", "2020-10-21 10:59:53,456 - example_logger - ERROR - There was an exception in zero_divide\n", "Traceback (most recent call last):\n", " File \"\", line 12, in wrapper\n", " return function(*args, **kwargs)\n", " File \"\", line 3, in zero_divide\n", " 1 / 0\n", "ZeroDivisionError: division by zero\n", "2020-10-21 10:59:53,456 - example_logger - ERROR - There was an exception in zero_divide\n", "Traceback (most recent call last):\n", " File \"\", line 12, in wrapper\n", " return function(*args, **kwargs)\n", " File \"\", line 3, in zero_divide\n", " 1 / 0\n", "ZeroDivisionError: division by zero\n" ] } ], "source": [ "print (output)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "End of Exceptions notebook" ] } ], "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.9.7" } }, "nbformat": 4, "nbformat_minor": 4 }