# This module demonstrates Python exception handling # An exception is a runtime error, often due to incorrect user input # In the first example, we take a list that we assume to be a collection of numeric values representing # ages of people and use it to compute an average age. We want to make sure that the program won't # crash if it encounters a non-numeric value. ages = [18, 20, 'fred', 23, 45] # our input list with a bad value ('fred') inside values = len(ages) # this will be the divisor we use to compute the average sumAges = 0 # the running sum of ages in the list for age in ages: # for each age in the list, print age # print it out try: sumAges += age # try incrementing sumAges by age except: # We get here if something goes wrong. We don't look for a specific error in this # example. With my data, adding 'fred' to a list of integers causes one. Therefore, we # end up here. print 'got a bad value, skipping ' + str(age) values -= 1 # decrement number of valid ages by 1 print 'the average age is ' + str(sumAges / float(values)) # watch out for integer division!!