Python 2.7 Tutorial Pt 9

Python How To

In this tutorial I’ll explain how to perform error catching inside of Python 2.7. I’ll specifically review how to:

  • Raise your own exceptions
  • Catch any error, so that your program doesn’t crash
  • Review all of the possible errors that can occur in Python
  • Review the most common errors to look out for

Like always, a lot of code follows the video. If you have any questions or comments leave them below. And, if you missed my other Python Tutorials they are available here:

All of the Code from the Video Tutorial

#! /usr/bin/python

import exceptions

class Dog:
__secret = 2

def makingErrors():

# Output a list of all the built in exceptions that trigger errors
for i in dir(exceptions):
print i

# How to raise an exception
# raise Exception(‘JustDisagreeable’)

# Raise an AttributeError exception
# Puppy = Dog()
# print Puppy.__secret

# Raise an IOError exception
# f = open(‘studentgrades.txt’)

# Raise an IndexError
# listEx = [1,2,3]
# print listEx[3]

# Raise a KeyError exception
#dictEx = ({“Age”:35, “Name”:’Derek’})
#print dictEx[“Age”]

# Raise a NameError exception
# print monkey

# Raise a SyntaxError exception
# print “Hello’

# Raise a TypeError exception
# print “Tomato” % 5

# Raise a ZeroDivisionError exception
# zeroDivisionErr = 1/0

# Stop a ZeroDivisionError exception
zeroDivision = 1/0
except ZeroDivisionError:
print “You can’t divide by zero”

# Stop multiple exceptions
zeroDivision = R/0
except (ZeroDivisionError,NameError), e:
print “You can only divide by non-zero numbers”
print e # Prints out the error message for the first exception caught

# Catch every exception
zeroDivision = R/0
print “You messed up”

# What happens if no exception is raised
halfDivision = 1.0/2.0
except (ZeroDivisionError,NameError):
print ‘You messed something up’
print halfDivision

# Use finally to always perform an action error or not
halfDivision = 1.0/2.0
except (ZeroDivisionError,NameError):
print ‘You messed something up’
print halfDivision
print “I always get to say something”


def main():

if __name__ == ‘__main__’: main()

Leave a Reply

Your email address will not be published.