next up previous contents
Next: String Data Up: Basic Principles of Python Previous: Namespaces and Variable Scoping   Contents


Exception Handling

Regardless how carefully you write your programs, when you start using them in a variety of situations, errors are bound to occur. Python provides a consistent method of handling errors, a topic often refered to as exception handling. When you're performing an operation that might result in an error, you can surround it with a try loop, and provide an except clause to tell python what to do when a particular error arises. While this is a fairly advanced concept, usually found in more complex languages, you can start using it in even your earliest python programs.

As a simple example, consider dividing two numbers. If the divisor is zero, most programs (python included) will stop running, leaving the user back at a system shell prompt, or with nothing at all. Here's a little python program that illustrates this concept; assume we've saved it to a file called div.py:

#!/usr/local/bin/python
x = 7
y = 0
print x/y
print "Now we're done!"
When we run this program, we don't get to the line which prints the message, because the division by zero is a ``fatal'' error:
% div.py
Traceback (innermost last):
  File "div.py", line 5, in ?
    print x/y
ZeroDivisionError: integer division or modulo
While the message may look a little complicated, the main point to notice is that the last line of the message tells us the name of the exception that occured. This allows us to construct an except clause to handle the problem:
x = 7
y = 0

try:
   print x/y
except ZeroDivisionError:
   print "Oops - I can't divide by zero, sorry!"

print "Now we're done!"
Now when we run the program, it behaves a little more nicely:
% div.py
Oops - I can't divide by zero, sorry!
Now we're done!
Since each exception in python has a name, it's very easy to modify your program to handle errors whenever they're discovered. And of course, if you can think ahead, you can construct try/except clauses to catch errors before they happen.


next up previous contents
Next: String Data Up: Basic Principles of Python Previous: Namespaces and Variable Scoping   Contents
Phil Spector 2003-11-12