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 moduloWhile 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.