Lesson 27. Error Handling

Practically all of the lessons in this tutorial do not use any error handling. This is for pedagogical reasons. In reality, you need to write your code in a robust way so it can handle errors gracefully.

Sources of errors include but are not limited to:

  • Database servers down

  • Network errors

  • Web servers down

  • Accessing directories and files that do not exist

  • Bad user input

  • That dude from the Allstate commercials

  • Gremlins. Not a joke.

Python, like many languages, implements error handling through the try/catch paradigm.

Try Catch Syntax

try:
    #business logic
except Exception as e:
    #print exception
else:
    #logic that runs if there is no error
finally:
    #any task that needs to execute reguardless of any errors raised.

Examples

Example #1: Basic Error Handling Hello World

Every error handling example starts with a divide by zero error.

numerator = 1
denominator = 0

try:
    numerator/denominator
except Exception as e:
    print(e)
else:
    print('Flip the values to see this message.')
finally:
    print('This is going to show anyway.')

Example #2: Using Built-in Exceptions

You can catch errors by using the Exception class, but if you really want to get fancy, you can catch specific errors. Catching errors this way allows you to develop gentler error messages than the intimidating trace you’d normally get with a bare error.

A list of built-in exceptions can be found here.

import os
import pandas as pd

script_dir = os.getcwd()
data_directory = 'data\\'
example_directory = 'BuiltInExceptionExample\\'
file_name = 'NonExistingFile.txt'
abs_file_path = os.path.join(script_dir, data_directory, example_directory, file_name)

try:
    pd.read_csv(abs_file_path)
except FileNotFoundError:
    print('No file here yo!')

Example #3: Using Exceptions In Modules

Finally, modules also come with exceptions.

import urllib.request
import urllib.error as ue

url = 'http://www.bobwakefield.com/'

try:
    urllib.request.urlopen(url)
except ue.URLError:
    print('Website does not exist.')py

Now you try it!

Don't copy and past. Type the code yourself!

Last updated