In [ ]:
import numpy as np

Exceptions

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

You've already seen some exceptions in the Debugging lesson. *

Many programs want to know about exceptions when they occur. For example, if the input to a program is a file path. If the user inputs an invalid or non-existent path, the program generates an exception. It may be desired to provide a response to the user in this case.

It may also be that programs will generate exceptions. This is a way of indicating that there is an error in the inputs provided. In general, this is the preferred style for dealing with invalid inputs or states inside a python function rather than having an error return.

Catching Exceptions

Python provides a way to detect when an exception occurs. This is done by the use of a block of code surrounded by a "try" and "except" statement.


In [1]:
def divide(numerator, denominator):
    result = numerator/denominator
    print("result = %f" % result)

In [2]:
divide(1.0, 0)


-------------------------------------------------------------------------
ZeroDivisionError                       Traceback (most recent call last)
<ipython-input-2-ebcb36a8aa31> in <module>()
----> 1 divide(1.0, 0)

<ipython-input-1-2d5d8a17c73f> in divide(numerator, denominator)
      1 def divide(numerator, denominator):
----> 2     result = numerator/denominator
      3     print("result = %f" % result)

ZeroDivisionError: float division by zero

In [3]:
def divide1(numerator, denominator):
    try:
        result = numerator/denominator
        print("result = %f" % result)
    except:
        print("You can't divide by 0!")

In [5]:
divide1(1.0, 'a')


You can't divide by 0!

In [ ]:
divide1(1.0, 2)

In [ ]:
divide1("x", 2)

In [13]:
def divide2(numerator, denominator):
    try:
        result = numerator / denominator
        print("result = %f" % result)
    except (ZeroDivisionError, TypeError) as err:
        print("Got an exception: %s" % err)

In [14]:
divide2(1, "X")


Got an exception: unsupported operand type(s) for /: 'int' and 'str'

In [ ]:
divide2("x, 2)

Why didn't we catch this SyntaxError?


In [ ]:
# Handle division by 0 by using a small number
SMALL_NUMBER = 1e-3
def divide3(numerator, denominator):
    try:
        result = numerator/denominator
    except ZeroDivisionError:
        result = numerator/SMALL_NUMBER
        print("result = %f" % result)
    except Exception as err:
        print("Different error than division by zero:", err)

In [ ]:
divide3(1,0)

In [ ]:
divide3("1",0)

What do you do when you get an exception?

First, you can feel relieved that you caught a problematic element of your software! Yes, relieved. Silent fails are much worse. (Again, another plug for testing.)

Generating Exceptions

Why generate exceptions? (Don't I have enough unintentional errors?)


In [15]:
import pandas as pd
def validateDF(df):
    """"
    :param pd.DataFrame df: should have a column named "hours"
    """
    if not "hours" in df.columns:
        raise ValueError("DataFrame should have a column named 'hours'.")

In [17]:
df = pd.DataFrame({'hours': range(10) })
validateDF(df)

In [18]:
df = pd.DataFrame({'years': range(10) })
validateDF(df)


-------------------------------------------------------------------------
ValueError                              Traceback (most recent call last)
<ipython-input-18-e3157253fec5> in <module>()
      1 df = pd.DataFrame({'years': range(10) })
----> 2 validateDF(df)

<ipython-input-15-960a19c537ec> in validateDF(df)
      5     """
      6     if not "hours" in df.columns:
----> 7         raise ValueError("DataFrame should have a column named 'hours'.")

ValueError: DataFrame should have a column named 'hours'.

Class exercise

Choose one of the functions from the last exercise. Create two new functions:

  • The first function throws an exception if there is a negative argument.
  • The second function catches an exception if the modulo operator (%) throws an exception and attempts to correct it by coercing the argument to a positive integer.