Web hosting top - 168 CHAPTER 8 EXCEPTIONS Invalid input: name
168 CHAPTER 8 EXCEPTIONS Invalid input: name ‘foo’ is not defined Please try again Enter the first number: 10 Enter the second number: 2 x/y is 5 And Finally . . . Finally, there is the finally clause. You use it to do housekeeping after a possible exception. It is combined with a try clause (but not an except clause): x = None try: x = 1/0 finally: print ‘Cleaning up…’ del x In the preceding, you are guaranteed that the finally clause will get executed, no matter what exceptions occur in the try clause. (The reason for initializing x before the try clause is that otherwise it would never get assigned a value because of the ZeroDivisionError. This would lead to an exception when using del on it within the finally clause, which you wouldn t catch.) If you run this, the cleanup comes before the program crashes and burns: Cleaning up… Traceback (most recent call last): File “C:pythondiv.py”, line 4, in ? x = 1/0 ZeroDivisionError: integer division or modulo by zero Exceptions and Functions Exceptions and functions work together quite naturally. If an exception is raised inside a function, and isn t handled there, it propagates (bubbles up) to the place where the function was called. If it isn t handled there either, it continues propagating until it reaches the main program (the global scope), and if there is no exception handler there, the program halts with an error message and some information about what went wrong (a stack trace). Let s take a look at an example: >>> def faulty(): … raise Exception(’Something is wrong’) … >>> def ignore_exception(): … faulty() …
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.