See All Titles |
![]() ![]() Exception HandlingExceptions are mostly used for error handling and event notification. They work by breaking the regular flow of a program and jumping to a special set of statements that handle the exception case. Python has many standard exceptions, which are exceptions already built into the language. Python also supports user-defined exceptions, which are exceptions created by users. The provided exceptions are almost no different from user-defined exceptionsthe only difference is that they are defined in one of the files in the standard library (exceptions.py). Any unexpected program behavior drives the interpreter to raise an exception. Many scenarios can help an exception to be raised, such as dividing a number by zero or reading from a nonexistent file. Note that the programmer can also manually raise exceptions with the raise statement. The default behavior of Python, when it encounters unhandled exceptions, is to terminate the program and to display a traceback message that describes the error condition. My goal in this chapter is to show you how to handle those exceptions. If you don't handle exceptions in your program, Python's interpreter returns a traceback message that shows the error message, the exception type, the function that contains the error, and the line of code that has caused the error. Hence, a complete history of what has caused the error is provided. So that you can start learning how Python raises and handles exceptions, I will define the following example: >>> a = { "a":1,"b":2} >>> def returnelement(element): print a[element] Now, we will call this function: >>> print returnelement("c") Note that "c" is not part of the a dictionary. Therefore, Python raises an exception that displays the following traceback message. Traceback (innermost last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in returnelement KeyError: c The last line of the traceback message tells us what exception was raised and what element has caused the exception to be triggered. If we run the previous code in the interpreter, the File clause is set to "<stdin>" by default because the code lines come from the keyboard and not from a file. However, if we run the code from an external file, the filename becomes part of the File clause. It is also worth mentioning that the line numbers are relative to the statement where the error occurred when the code was entered interactively. So, we get line 2 in the traceback because the exception occurred on the second line of the function, which was treated as a single statement. The outermost part of the trace says line 1 because the call to returnelement was treated as a one-line statement. Next to the filename, we have a line number, which is the line in which the error has been triggered. Next to the line number is the name of the function that caused the error. Tip
By handling exceptions, you can save a lot of time while testing your code. Exceptions can be handled by using either try/except or try/finally statements. The difference between them is that an except clause is only executed when an exception is raised, and a finally clause is always executed; it doesn't matter whether an exception is raised or not. Also, the try/finally block doesn't catch the exception like try/except can. Next is the standard structure for a try/except statement: try: <statements> except [<exception_name> [, <instance_variable>]]: <exception handling statements> [else: <statements executed only when no exception is raised>] The else block must be inserted after the last exception block, and it is only executed when the try block doesn't raise any errors. In order to handle multiple exceptions, you can use multiple except clauses for the same try block. The next example raises an error message whenever it can't find a given element. >>> name = ["Andre","Renata","Joao","Rebecca"] >>> def getname(order): try: if order < 10: data = name[order] else: file = open("names.txt") data = file.readline() file.close() return data except IndexError: print "This name is not in the list." except IOError: print "The file names.txt does not exist." >>> getname(0) "Andre" >>> getname(8) "This name is not in the list." >>> getname(20) "The file names.txt does not exist." Python syntax also enables you to use a single except clause that handles all exceptions. The general syntax for the except clause for handling all exceptions is to not specify any exception types at all, such as try: <statements> except: <exception handling statements> Next, you have the syntax and an example for handling multiple exception types. except (exception1, exception 2, exception 3)[, variable]: >>> name = ["Andre","Renata","Joao","Rebecca"] >>> def getname(order): try: if order < 10: data = name[order] else: file = open("names.txt") data = file.readline() file.close() return data except (IndexError, IOError): print "Data not available." >>> getname(8) "Data not available." >>> getname(20) "Data not available." You can also use try/except statements to ignore exceptions. The next structure uses a pass statement to ignore an exception whenever it gets raised. However, note that if an exception is raised, all the remaining statements in the try block will not be executed. try: <statements> except <exception_name>: pass In the next example, we use exceptions not to catch and handle an unexpected error, but to ignore errors that we know might happen when the code is running. As you can see, an exception is raised every time you try to convert a text string into a float number in line 6. However the pass statement in line 8 simply ignores the problem. 1: >>> import string 2: >>> list = ["1","3","Monkey","Parrot","10"] 3: >>> total = 0 4: >>> for z in list: 5: >>> try: 6: >>> total = total + string.atof(z) 7: >>> except: 8: >>> pass 9: >>> print total 10: 14
|
Index terms contained in this sectionexceptionshandling 2nd 3rd raising handling exceptions 2nd 3rd pass statement raise statement raising exceptions statements pass raise try/except 2nd try/finally syntax handling multiple exceptions try/except statement 2nd try/finally statement |
© 2002, O'Reilly & Associates, Inc. |