My web site - CHAPTER 8 EXCEPTIONS 167 Here the loop

CHAPTER 8 EXCEPTIONS 167 Here the loop is only broken (by the breakstatement in the elseclause) when no exception is raised. In other words, as long as something wrong happens, the program keeps asking for new input. The following is an example run: Enter the first number: 1 Enter the second number: 0 Invalid input. Please try again. Enter the first number: ‘foo’ Enter the second number: ‘bar’ Invalid input. Please try again. Enter the first number: baz Invalid input. Please try again. Enter the first number: 10 Enter the second number: 2 x/y is 5 As mentioned previously, an alternative to using an empty exceptclause is to catch all exceptions of the Exception class (which will catch all exceptions of any subclass as well). You cannot be 100 percent certain that you ll catch everything then, because the code in your try/except statement may be naughty and use the old-fashioned string exceptions, or perhaps create a custom exception that doesn t subclass Exception. However, if you go with the except Exception version, you can use the technique from the section Catching the Object, earlier in this chapter, to print out a more instructive error message in your little division program: while 1: try: x = input(’Enter the first number: ‘) y = input(’Enter the second number: ‘) value = x/y print ‘x/y is’, value except Exception, e: print ‘Invalid input:’, e print ‘Please try again’ else: break The following is a sample run: Enter the first number: 1 Enter the second number: 0 Invalid input: integer division or modulo by zero Please try again Enter the first number: ‘x’ Enter the second number: ‘y’ Invalid input: unsupported operand type(s) for /: ’str’ and ’str’ Please try again Enter the first number: foo
From our experience, we can recommend PHP Web Hosting services, if you need affordable webhost to host and run your web application.

Comments are closed.