Dedicated web hosting - 166 CHAPTER 8 EXCEPTIONS try: x =
166 CHAPTER 8 EXCEPTIONS try: x = input(’Enter the first number: ‘) y = input(’Enter the second number: ‘) print x/y except: print ‘Something wrong happened…’ Now you can do practically whatever you want: Enter the first number: “This” is *completely* illegal 123 Something wrong happened… Caution Catching all exceptions like this is risky business because it will hide errors you haven t thought of as well as those you re prepared for. It will also trap attempts by the user to terminate execution by Ctrl-C, attempts by functions you call to terminate by sys.exit, and so on. In most cases, it would be better to use except Exception, e and perhaps do some checking on the exception object, e. When All Is Well In some cases, it can be useful to have a block of code that is executed unless something bad happens; as with conditionals and loops, you can add an else clause: try: print ‘A simple task’ except: print ‘What? Something went wrong?’ else: print ‘Ah…It went as planned.’ If you run this, you get the following output: A simple task Ah…It went as planned. With this else clause, you can implement the loop hinted at in the section Catching Two Exceptions with One Block, earlier in this chapter: while 1: try: x = input(’Enter the first number: ‘) y = input(’Enter the second number: ‘) value = x/y print ‘x/y is’, value except: print ‘Invalid input. Please try again.’ else: break
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.