"""Exceptions http://openbookproject.net/thinkcs/python/english2e/ch11.html#exceptions See also: http://docs.python.org/tutorial/errors.html """ # Whenever a runtime error occurs, it creates an exception. # The program stops running and Python prints out the traceback, # which ends with the exception that occured. # Dividing by zero creates an exception: print 1/0 # And so does accessing a nonexistent element in a list: a = [] print a[5] # As does trying to modify a string: s = 'python' s[0] = 'j' # Sometimes we want to execute an operation that might cause an exception, # but we don't want the program to stop. We can handle the exception using # the try and except statements. # For example: file_name = raw_input('Enter a file name: ') try: file_handle = open(file_name, "r") except: print 'There is no file named', filename def exists(file_name): try: f = open(file_name) f.close() return True except: return False # Here's a snippet of code that prompts the user for a number and # continues to ask for a number until a valid number is provided while True: try: x = int(raw_input("Please enter an integer: ")) break except ValueError: print "Oops! That was no valid number. Try again..." # note the use of the break statement - it exits the loop in which # it is put # the 'raise' statement is used to create an exception: age = input('Please enter your age: ') if age < 0: raise ValueError, '%s is not a valid age' % age # each exception has a type, that identifies the nature of the error # A complete list of exceptions is found at: # http://docs.python.org/library/exceptions.html