Tutorials
Hands-On Python
Hands-On Python
  • Hands-On Python Tutorial For Real-World Business Analytics Problems
  • Preface
    • Section I. A Note From The Author
    • Section II. Tutorial Overview
    • Section III. What Is The Preflight Checklist?
    • Section IV. Supplimentery Material
  • Preflight Checklist
    • Section V. Select Your Difficulty Setting
    • Section VI. Download Anaconda
    • Section VII. Download PyCharm (Optional)
    • Section VIII. Download SQL Server Developer Edition
    • Section IX. Configure Database Environment
    • Section X. Download The Source Code
    • Section XI. Starting JupyterLab
    • Section XII. How To Get Help With This Tutorial
  • Language Basics
    • Lesson 1. Obligatory Hello World
    • Lesson 2. Code Comments
    • Lesson 3. Data Types
    • Lesson 4. Variables
    • Lesson 5. String Concatenation
    • Lesson 6. Arithmetic Operators
    • Lesson 7. Making Decisions
    • Lesson 8. Control Flow With if-elif-else
    • Lesson 9. Control Flow With while
    • Lesson 10. Data Structures Part I: List
    • Lesson 11. Data Structures Part II: Tuples
    • Lesson 12. Data Structures Part III: Dictionaries
    • Lesson 13. Looping With for
    • Lesson 14. Functions
    • Lesson 15. Importing Modules
    • Lesson 16. Python Programming Standards
  • Advanced Topics
    • Lesson 17. Functional Programing With map
    • Lesson 18. Generators
    • Lesson 19. Comprehensions
    • Lesson 20. Basic File Operations
    • Lesson 21. Working With Data In Numpy
    • Lesson 22. Working With Data In Pandas
    • Lesson 23. Working With JSON
    • Lesson 24. Making File Request Over HTTP And SFTP
    • Lesson 25. Interacting With Databases
    • Lesson 26. Saving Objects With Pickle
    • Lesson 27. Error Handling
    • Lesson 28. Bringing It All Together
  • Solutions To Real World Problems
    • Lesson 29. Download A Zip File Over HTTP
    • Lesson 30. Looping Over Files In A Directory
    • Lesson 31. Convert Comma Delmited Files To Pipe Delimited
    • Lesson 32. Combining Multiple CSVs Into One File
    • Lesson 33. Load Large CSVs Into Data Warehouse Staging Tables
    • Lesson 34. Efficiently Write Large Database Query Results To Disk
    • Lesson 35. Working With SFTP In The Real World
    • Lesson 36. Executing Python From SQL Server Agent
Powered by GitBook
On this page
  • Try Catch Syntax
  • Examples
  • Now you try it!
  1. Advanced Topics

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.

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!

PreviousLesson 26. Saving Objects With PickleNextLesson 28. Bringing It All Together

Last updated 3 years ago

A list of built-in exceptions can be found .

here