# This module demonstrates additional Python exception handling. # In this example, we not only look for a TypeError but also a ValueError. # A type error will be raised automatically if we try to do operations that are # not permitted for a certain type (like adding a string to an integer). A ValueError # is not necessarily raised automatically--in our case below, we will raise one if one # of our data elements is outside of a permissible range for our problem. You can # handle more than one type of exception within a single try block--you just follow # the try section with multiple except sections. ages = [18, 20, 'fred', 23, -1, 45] # our input list with 2 bad values ('fred' and -1) 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: if age < 0: # now we also protect against bad numeric age values raise ValueError() # if we get here, then we jump to except ValueError: below # If we got this far, then we don't have a bad integer value, but we still might # have non-numeric data in age. If that happens, then a TypeError exception will # be automatically generated by the following line of code: sumAges += age # try incrementing sumAges by age except TypeError: # We get here if some statement in the try block does something inappropriate with # specific data types. In this sample program, adding an integer and a string generates # a TypeError exception. We handle it here and then continue the for loop. print 'got a bad value, skipping ' + str(age) values -= 1 # decrement number of valid ages by 1 except ValueError: # We get here when the if statement in the try block finds an age value less than 0. # When that happens, we manually generate a ValueError exception # by using the raise ValueError() statement. As soon as the exception is generated, # we end up here. values -= 1 # decrement number of valid ages by 1 print 'got a bad value: ' + str(age) + ' is not greater than 0' try: # To be safe, we also check to make sure that we do not have a divide by zero problem. This # can happen if our input list is empty or if all the values in the list are bad (strings or # integer values less than or equal to 0). In either case, values will be 0. # Looks picky, but it can happen! Protect yourself!! print 'the average age is ' + str(sumAges / float(values)) # watch out for integer division!! except ZeroDivisionError: print 'Cannot compute an average age because there was no valid input'