# exceptions.py # Exceptions # Whenever a runtime error occurs, it creates an exception. # Usually, the program stops and Python prints an error message. # For example, dividing by zero creates an exception: # >>> print 55/0 # ZeroDivisionError: integer division or modulo # So does accessing a nonexistent list item: # # >>> a = [] # >>> print a[5] # IndexError: list index out of range # # Or accessing a key that isn't in the dictionary: # # >>> b = {} # >>> print b['what'] # KeyError: what # In each case, the error message has two parts: # # 1. the type of error before the colon, and # 2. specifics about the error after the colon. # # Normally Python also prints a traceback of where the program was at # the time of error, but we have omitted that from the examples. # # Sometimes we want to execute an operation that could 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, we might prompt the user for the name of a file and # then try to open it. If the file doesn't exist, we don't want # the program to crash; we want to handle the exception. Here is one # way to handle the situation: filename = raw_input('Enter a file name: ') try: f = open (filename, "r") except: print 'There is no file named', filename # The try statement executes the statements in the first block. # If no exceptions occur, it ignores the except statement. If any # exception occurs, it executes the statements in the except branch # and then continues. # We can encapsulate this capability in a function: exists takes a # filename and returns True if the file exists, False if it doesn't: # def exists(filename): try: f = open(filename) f.close() return 1 except: return 0