Python Bibliotheca
Python resources for teachers and students.

Simple exception handling

Here's a simple example demonstrating how an exception can be used to control the flow of a program and make sure that the user's entry is valid. The program will continue getting input from the user until her or she enters a Control-D character. At that point, the except EOFError executes, the program breaks out of the while loop, and the sum is printed. If the user enters a non-integer, then the except code executes and the user is informed of the mistake.

Handling exceptions gracefully is a very important part of creating high-quality software. More on exception handling can be found in Chapter 11, Section 5 of How to Think Like a Computer Scientist: Learning with Python.

Sample code

sum = 0
print "Enter a series of integers. Press Ctrl-D to print the sum."
while 1:
    try:
        number = raw_input("> ")
        sum += int(number)
    except EOFError:   # Catch the Ctrl-D
        break
    except:   # Trap all other errors
        print "Bad input. '%s' is not an integer." % number
print
print "The sum is %s." % sum

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster