Web space - CHAPTER 8 EXCEPTIONS 163 Look, Ma, No

CHAPTER 8 EXCEPTIONS 163 Look, Ma, No Arguments! If you have caught an exception but you want to raise it again (pass it on, so to speak), you can call raise without any arguments. (You can also supply the exception explicitly if you catch it, as explained in the section Catching the Object, later in this chapter.) As an example of how this might be useful, consider a calculator class that has the capability to muffle ZeroDivisionErrors. If this behavior is turned on, the calculator prints out an error message instead of letting the exception propagate. This is useful if the calculator is used in an interactive session with a user, but if it is used internally in a program, raising an exception would be better. Therefore the muffling can be turned off. Here is the code for such a class: class MuffledCalculator: muffled = 0 def calc(self, expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print ‘Division by zero is illegal’ else: raise Note If division by zero occurs and muffling is turned on, the calc method will (implicitly) return None. In other words, if you turn on muffling, you should not rely on the return value. The following is an example of how this class may be used, both with and without muffling: >>> calculator = MuffledCalculator() >>> calculator.calc(’10/2′) 5 >>> calculator.calc(’10/0′) # No muffling Traceback (most recent call last): File ““, line 1, in ? File “MuffledCalculator.py”, line 6, in calc return eval(expr) File ““, line 0, in ? ZeroDivisionError: integer division or modulo by zero >>> calculator.muffled = 1 >>> calculator.calc(’10/0′) Division by zero is illegal As you can see, when the calculator is not muffled, the ZeroDivisionError is caught but passed on.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Comments are closed.