Error handling

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

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 different approaches
  • Find what errors might occur

Different commute types in the city

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?

  • average() expects a list or set
  • 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]}
print(average(sales_dict))

Traceback with TypeError

Intermediate Python for Developers

Previous error-handling

  • 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.")
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

print(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...