Error handling

Intermediate Python for Developers

George Boorman

Curriculum Manager, DataCamp

Pandas traceback

Traceback showing code that intentionally returns an error

  • except, raise

  • Try to anticipate how errors might occur

Intermediate Python for Developers

Design-thinking

  • How might people use our custom function?
  • Test these different approaches
  • Find what errors occur

Path created by walking across some grass to cut out a corner

1 Image credit: https://www.flickr.com/photos/140641142@N05/
Intermediate Python for Developers

Error handling in custom functions

def average(values):
    # Calculate the average
    average_value = sum(values) / len(values)
    return average_value
Intermediate Python for Developers

Where might they go wrong?

  • Provide more than one argument
  • Use the wrong data type
Intermediate Python for Developers

Where might they go wrong?

sales_dict = {"cust_id": ["JL93", "MT12", "IY64"],
              "order_value": [43.21, 68.70, 82.19]}
average(sales_dict)

Traceback with TypeError

Intermediate Python for Developers

Error-handling techniques

  • Control flow if, elif, else
  • Docstrings
Intermediate Python for Developers

try-except

def average(values):

try:
# Code that might cause an error average_value = sum(values) / len(values) return average_value
except:
# Code to run if an error occurs print("average() accepts a list or set. Please provide a correct data type.")
average(sales_dict)
average() accepts a list or set. Please provide a correct data type.
Intermediate Python for Developers

raise

def average(values):
    # Check data type
    if type(values) in ["list", "set"]:

# Run if appropriate data type was used average_value = sum(values) / len(values) return average_value
Intermediate Python for Developers

raise

def average(values):
    # Check data type
    if type(values) in ["list", "set"]:

# Run if appropriate data type was used average_value = sum(values) / len(values) return average_value
else: # Run if an Exception occurs raise
Intermediate Python for Developers

raise TypeError

def average(values):
    # Check data type
    if type(values) in ["list", "set"]:

# Run if appropriate data type was used average_value = sum(values) / len(values) return average_value
else: # Run if an Exception occurs raise TypeError("average() accepts a list or set, please provide a correct data type.")
Intermediate Python for Developers

raise TypeError output

average(sales_dict)

TypeError output showing the custom message to provide the correct data type

Intermediate Python for Developers

try-except vs. raise

try-except

  • Avoid errors being produced
  • Still execute subsequent code

raise

  • Will produce an error
  • Avoid executing subsequent code
Intermediate Python for Developers

Let's practice!

Intermediate Python for Developers

Preparing Video For Download...