164 CHAPTER 8 EXCEPTIONS More Than One (Web design conference)

164 CHAPTER 8 EXCEPTIONS More Than One except Clause If you run the program from the previous section again and enter a nonnumeric value at the prompt, another exception occurs: Enter the first number: 10 Enter the second number: “Hello, world!” Traceback (most recent call last): File “exceptions.py”, line 4, in ? print x/y TypeError: unsupported operand type(s) for /: ‘int’ and ’str’ Because the exceptclause only looked for ZeroDivisionError exceptions, this one slipped through and halted the program. To catch this as well, you can simply add another except clause to the same try/except statement: try: x = input(’Enter the first number: ‘) y = input(’Enter the second number: ‘) print x/y except ZeroDivisionError: print “The second number can’t be zero!” except TypeError: print “That wasn’t a number, was it?” This time using an if statement would be more difficult. How do you check whether a value can be used in division? There are a number of ways, but by far the best way is, in fact, to simply divide the values to see if it works. Also notice how the exception handling doesn t clutter the original code; adding lots of if statements to check for possible error conditions could easily have made the code quite unreadable. Catching Two Exceptions with One Block If you want to catch more than one exception type with one block, you can specify them all in a tuple, as follows: try: x = input(’Enter the first number: ‘) y = input(’Enter the second number: ‘) print x/y except (ZeroDivisionError, TypeError): print ‘Your numbers were bogus…’ In the preceding code, if the user either enters a string or something other than a number, or if the second number is zero, the same error message is printed. Simply printing an error message isn t very helpful, of course. An alternative could be to keep asking for numbers until the division works. I show you how to do that in the section When All Is Well, later in this chapter.
You want to have a cheap webhost for your apache application, then check apache web hosting services.

Comments are closed.