Day 37: Introduction to Error Handling in Python

When we write our codes, we hope our codes can catch those invalid arguments. In Python, when we pass in invalid arguments, the Python will throw their error messages. However, not every one of the error messages is user-friendly such as the TypeError.

Here, we learn how to write our own error messages in our functions, by providing a meaningful or useful error messages to users.

Errors and Exceptions
– Exceptions are caught during execution.
– Method to catch exceptions is using try-except clause.
– Python runs the code following the try block. If it cannot or if there is an exception, run the code following except block.

See below example taken from DataCamp:

In two separate occasions, we try to call the sqrt() function with correct value and with incorrect value. Then, see whether the error message we want to print out shows up when the code runs into the except block.

# First call
sqrt(10.0)

# Second call
sqrt('hi')

The results of the executions show as below. The first execution uses the correct integer or float value and returns us the result as per expected. Then, second execution the sqrt() function has an invalid argument, a string format.

In an exercise I did in the DataCamp’s online learning, it combined the function called count_countries(), the DataFrame which contained the countries, a dictionary to hold the result and a try-except block to handle the errors.

# Define count_entries()
def count_entries(df, col_name='lang'):
    """Return a dictionary with counts of
    occurrences as value for each key."""

    # Initialize an empty dictionary: cols_count
    cols_count = {}

    # Add try block
    try:
        # Extract column from DataFrame: col
        col = df[col_name]
        
        # Iterate over the column in dataframe
        for entry in col:
    
            # If entry is in cols_count, add 1
            if entry in cols_count.keys():
                cols_count[entry] += 1
            # Else add the entry to cols_count, set the value to 1
            else:
                cols_count[entry] = 1
    
        # Return the cols_count dictionary
        return cols_count

    # Add except block
    except:
        print('The DataFrame does not have a ' + col_name + ' column.')

# Call count_entries(): result1
result1 = count_entries(tweets_df, 'lang')

# Print result1
print(result1)

#Output: {'et': 1, 'und': 2, 'en': 97}

Another error handling method is using raise block.

For example, when we do not want to accept a negative value, we can do a condition checks using if statement and raise the error if value is less than zero.

# Define shout_echo
def shout_echo(word1, echo=1):
    """Concatenate echo copies of word1 and three
    exclamation marks at the end of the string."""

    # Raise an error with raise
    if echo < 0:
        raise ValueError('echo must be greater than 0')

    # Concatenate echo copies of word1 using *: echo_word
    echo_word = word1 * echo

    # Concatenate '!!!' to echo_word: shout_word
    shout_word = echo_word + '!!!'

    # Return shout_word
    return shout_word

# Call shout_echo
shout_echo("particle", echo=5)

To improve the code I did in my exercise, let us add the raise block into the code by checking if the DataFrame contains the column called ‘col_name’.

# Define count_entries()
def count_entries(df, col_name='lang'):
    """Return a dictionary with counts of
    occurrences as value for each key."""
    
    # Raise a ValueError if col_name is NOT in DataFrame
    if col_name not in df.columns:
        raise ValueError ('The DataFrame does not have a ' + col_name + ' column.')

    # Initialize an empty dictionary: cols_count
    cols_count = {}
    
    # Extract column from DataFrame: col
    col = df[col_name]
    
    # Iterate over the column in DataFrame
    for entry in col:

        # If entry is in cols_count, add 1
        if entry in cols_count.keys():
            cols_count[entry] += 1
            # Else add the entry to cols_count, set the value to 1
        else:
            cols_count[entry] = 1
        
        # Return the cols_count dictionary
    return cols_count

# Call count_entries(): result1
result1 = count_entries(tweets_df)

# Print result1
print(result1)

#Output: {'et': 1, 'und': 2, 'en': 97}

Summary of the day:

  • Errors and exceptions handling.
  • try-except statement.
  • raise statement.

Advertisements