|
ExceptionsObject Composition Table Of Contents Builtin Functions
an exception and handle thhandling exceptions so your program can take counter measures to deal with the specific event. If the exception is not handled, the program will abort with a runtime error. Catching ExceptionsA classic use of exceptions is in dealing with run-time errors.
For example, if you attempt to access a list element that is out of range, Python raises the myList = [ 12, 50, 5, 17 ] print myList[ 4 ] we attempt to print the item of the list at element $4$. But the legal range of indices is [0..3]. In this case, Python will automatically raise a specific exception to flag an error. Traceback (most recent call last): File "<stdin>", line 1, in ? IndexError: list index out of range By default, the exception causes the program to abort. To prevent this from happening, we can catch the exception and take counter measures such as printing a warning message. try: myList = [ 12, 50, 5, 17 ] print myList[ 4 ] except IndexError: print "Error: Index out of range." How It WorksThe
Exception handlers are very useful when extracting user input. while True: try: value = int(raw_input("Enter an integer value: ")) break except ValueError: print "Oops! That was not an integer. Try again..." Multiple Except BlocksA try: x = 0 myList = [ 12, 50, 5, 17 ] print myList[ 3 ] / x except IndexError: print "Error: Index out of range." except ZeroDivisionError: print "Error: Attempt to divide by zero." In this case, we’ve added an exception handler to also catch divisions by zero. Without the handler, the program would abort since our program is incorrect and we are attempting to divide by zero. The last try: x = 0 myList = [ 12, 50, 5, 17 ] print myList[ 3 ] / x except IndexError: print "Error: Index out of range." except ZeroDivisionError: print "Error: Attempt to divide by zero." except: print "Error: An exception was raised." In some instances we may want to abort the program any way, even if we catch the exception. By catching the exception first, we can abort cleanly to clean up any loose ends. For example, if we have an output file opened, we may want to close it before the program aborts so the buffer is flushed. Handlers at Different ScopesThe def average( valueList ) : total = 0 for x in valueList : total = total + x try: avg = total / len( valueList ) return avg except ZeroDivisionError: return 0.0 myList = [ 12, 50, 5, None, 17 ] try: listAvg = average( myList ) print "The average = ", listAvg except TypeError: print "An invalid type was in the list." Python defines a number of built-in exceptions that can be raised automatically during program execution: Raising ExceptionsWe have seen several instances when Python automatically raises exceptions during program execution. But you can also def min( value1, value2 ) : if value1 == None or value2 == None : raise TypeError if value1 < value2 : return value1 else: return value2 Python also defines the def average( valueList ) : total = 0 assert len( valueList ) > 0, "Empty list in average()." for x in valueList : total = total + x try: avg = total / len( valueList ) return avg If the test len( valueList ) > 0 fails, an assert <test>, <data> where the | |
© 2006 - 2008: Rance Necaise - Page last
modified on September 30, 2006, at 06:15 PM
|