In [1]:
import numpy as np
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.
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 [4]:
def divide(numerator, denominator):
result = numerator/denominator
print("result = %f" % result)
In [5]:
divide(1.0, 0)
In [18]:
def divide1(numerator, denominator):
try:
GARBAGE
result = numerator/denominator
print("result = %f" % result)
except (ZeroDivisionError, NameError) as err:
import pdb; pdb.set_trace()
print("You can't divide by 0! or use GARBAGE.")
In [19]:
divide1(1.0, 'a')
In [15]:
print(err)
In [6]:
divide1(1.0, 2)
In [7]:
divide1("x", 2)
In [8]:
def divide2(numerator, denominator):
try:
result = numerator / denominator
print("result = %f" % result)
except (ZeroDivisionError, TypeError) as err:
print("Got an exception: %s" % err)
In [9]:
divide2(1, "X")
In [3]:
#divide2("x, 2)
In [1]:
# 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 [12]:
divide3(1,0)
In [13]:
divide3("1",0)
In [14]:
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 [15]:
df = pd.DataFrame({'hours': range(10) })
validateDF(df)
In [23]:
class SeattleCrimeError(Exception):
pass
In [21]:
b = False
if not b:
raise SeattleCrimeError("There's been a crime!")