''' exceptions.py Jeff Ondich, 21 September 2009 This program gives a brief illustration of the use of exceptions arguments in Python. To test the exceptions, try entering a non-integer at the first prompt, or the name of a non-existent file at the second prompt. ''' import math # Here, an exception may be raised when we try to convert # a string into a real number (float). Thus, we put our # dangerous operation in a "try" block, and handle the # exception, if it occurs, in the "except" block. numberString = raw_input('Number, please: ') try: number = float(numberString) except Exception, e: print numberString, 'is not a number.' print 'Here is what the Python interpreter says:', e print '(See how my error message is more helpful (and more helpful) than Python\'s?)' exit() # Here, we might get an exception when we try to compute # a square root. try: squareRoot = math.sqrt(number) except Exception, e: print 'Something about', number, 'made sqrt() sad. I bet it was negative.' print 'Alternatively, here is what Python says:', e exit() print 'The square-root of', number, 'is', squareRoot # Finally, if you try to open a file that doesn't exist, an # exception will be raised. fileName = raw_input('Name a file, please: ') try: f = open(fileName) except Exception, e: print 'There has been some trouble opening', fileName, '. Did you get the name right?' print 'Or, if you want the official story:', e exit() n = 0 for line in f: n = n + 1 f.close() print 'There are', n, 'lines in', fileName