CHAPTER 8 EXCEPTIONS (Best web site) 165 Note that the
CHAPTER 8 EXCEPTIONS 165 Note that the parentheses around the exceptions in the except clause are important; a common error is to omit them, in which case you may end up with something other than what you want. For an explanation, see the next section, Catching the Object. Catching the Object If you want access to the exception itself in an exceptclause, you can use two arguments instead of one. (Note that even when you are catching multiple exceptions, you are only supplying except with one argument a tuple.) This can be useful (for example) if you want your program to keep running, but you want to log the error somehow (perhaps just printing it out to the user). The following is an example program that prints out the exception (if it occurs), but keeps running: try: x = input(’Enter the first number: ‘) y = input(’Enter the second number: ‘) print x/y except (ZeroDivisionError, TypeError), e: print e The exceptclause in this little program again catches two types of exceptions, but because you also explicitly catch the object itself, you can print it out so the user can see what happened. (You see a more useful application of this later in this chapter, in the section When All Is Well. ) A Real Catchall Even if the program handles several types of exceptions, some may still slip through. For example, using the same division program, simply try to press Enter at the prompt, without writing anything. You should get a stack trace somewhat like this: Traceback (most recent call last): File ‘exceptions.py’, line 3, in ? x = input(’Enter the first number: ‘) File ‘
Check Tomcat Web Hosting services for best quality webspace to host your web application.