Exception Handling in Python
By: Sadrach Pierre
Tags: Python, Software Development, Technology, Data Science, Programming

Exception handling is the method of programmatically responding to unusual conditions that require special processing. In python, it is straight forward to implement exception handling for a wide variety of error types. In this post, we will discuss how to implement exception handling in python.

Let’s get started!

First, let’s consider the following list of integers:

my_list1 = [1, 2, 3, 4, 5]

We can iterate over the list and print the elements using a ‘for-loop’:

for value in my_list1:

print(value)

Within the ‘for-loop’ we can also perform operations and print the results. Let’s calculate the square of each element and print the result;

for value in my_lis1t:

square = value**2

print(value, square)

Suppose our list also contained the string value, ‘6’:

my_list2 = [1, 2, 3, 4, 5, '6']

Let’s try to calculate the square of each element in this new list. This will return a ‘TypeError’:

for value in my_list2:

square = value**2

print(value, square)

The error specifies the line of problematic code:

square = value**2

The ‘TypeError’ was raised because the operand ‘str’ is not supported for the ‘**’ power operator. Suppose we want our code to have a way of processing string valued integers without throwing an error. This is where exception handling comes into play. We can handle the ‘TypeError’ using the python keywords try and except. First, let’s try to square and print each value:

for value in my_list2:

try:

square = value**2

print(value, square)

When we get a ‘TypeError’, we use the except keyword to handle the ‘TypeError’. Since the string contains a numerical value, we can use the ‘int()’ method to convert the string into an integer and calculate the square within the exception:

for value in my_list2:

try:

square = value**2

print(value, square)

except(TypeError):

square = int(value)**2

print(value, square)

It’s worth noting that the way we handle errors highly depends on the error type and the type of data we are processing.

Next, suppose our list contains a word or another type like a list. We want to be able handle these errors without having our code fail to produce any output. Let’s consider the following list which contains the string ‘##’:

my_list3 = [1, 2, 3, 4, 5, '##']

If we try to loop over this new list and calculate the square we get a ‘ValueError’:

for value in my_list3:

try:

square = value**2

print(value, square)

except(TypeError):

square = int(value)**2

print(value, square)

This error is saying that we can’t convert the string, ‘##’, into an integer. We need to write extra processing for this error type. For example, we can replace the string with some filler value, like 0 or ‘NaN’:

import numpy as np

for value in my_list3:

try:

square = value**2

print(value, square)

except(TypeError):

square = np.nan

print(value, square)

Let’s consider another example of exception handling. Suppose we have the following list of strings containing programming languages:

my_list4 = ['python c++ java', 'SQL R scala', 'pandas keras sklearn']

We can use the ‘split()’ method to split the strings and add the text ‘is awesome’ using the ‘+’ operator:

for value in my_list4:

print([i +' is awesome' for i in value.split()])

Since the ‘split()’ method is a string object method, an ‘AttributeError’ will be raised if there are non-string values in our list. Let’s add a dictionary to our list and run our code again:

my_list4 = ['python c++ java', 'SQL R scala', 'pandas keras sklearn', {'language': ''golang'}]

for value in my_list4:

print([i +' is awesome' for i in value.split()])

The error says the ‘dict()’ object has no attribute ‘split()’. Let’s write some try/except logic to handle this error:

my_list4 = ['python c++ java', 'SQL R scala', 'pandas keras sklearn', {'language': 'golang ruby julia'}]

for value in my_list4:

try:

print([i +' is awesome' for i in value.split()])

except(AttributeError):

print([i +' is awesome' for i in value['language'].split()])

I’ll stop here but I encourage you to play around with the code yourself.

CONCLUSION

To summarize, in this post we discussed exception handling in python. We showed how to use try/except keywords and error types to handle bad values in data. We look at examples of handling the ‘TypeError’ and the ‘AttributeError’. I encourage you to look in to the additional error types and how to handle them. Additional error types include ‘SyntaxError’, ‘ZeroDivisionError’, ‘FileNotFoundError’ and much more. I hope you found this post useful/interesting. The code in this post is available on GitHub. Thank you for reading!