# File: except.py # Program to read in a positive number # and complain when the input isn't that # # Matt Bishop, MHI 289I, Winter 2018 # read in a positive number # def getposnumber(): # read the input and convert it to an integer # notice we do *not* catch the error here; it # is to be caught by the caller try: n = int(raw_input("type a number: ")) except ValueError: print "ValueError in getposnumber()" n = 0 # n = int(raw_input("type a number: ")) # now just return it return n # # the program itself # def main(): # # loop to show how to break out of an infinite loop # while True: # read in a positive integer # handle any exceptions (relatively) intelligently try: n = getposnumber() # exception: bad value (string, invalid number) except ValueError as msg: print msg, "-- try again!" # give it another chance # exception: end of file except EOFError as msg: print msg, "-- bye!" # quit break # some other exception except Exception as mesg: print mesg, "-- ignoring!" # ignore the problem # no exception -- print the number else: if n <= 0: print "You typed a non-positive number" else: print "Read", n finally: print "\n-----------------------\n" main()