Exception in notes of python basic tutorial, and python basic tutorial
When a raise statement is used to raise an Exception, you can use a class (which should be a subclass of Exception) or an instance parameter as the raise object. When a class is used, the program automatically creates an instance, as shown in figure
>>> Raise Exception ('hyperdrive overload ')
Traceback (most recent call last ):
File "<pyshell #8>", line 1, in <module>
Raise Exception ('hyperdrive overload ')
Exception: hyperdrive overload
You can use try/try t to capture exceptions, as shown in figure
Try: x = input (":") y = input (":") print x/yt t ZeroDivisionError: print "hello exception" # The result is as follows: >>:10: 25 >>>: 1: 0 hello exception
Raise an exception again, as shown in figure
Class MuffledCalculator: muffled = False def calc (self, expr): try: return eval (expr) limit t ZeroDivisionError: if self. muffled: # If the shield flag is enabled, the print "Division by zero is illegal" else: # If the shield flag is not enabled, the raise exception is thrown again. # The result is as follows: >>> clc = MuffledCalculator () >>> clc. calc ('000000') 5 >>> clc. calc ('200') # Traceback (most recent call last): File "<pyshell #17>", line 1, in <module> clc. calc ('000000') # File not blocked "E: \ work \ Code \ python \ test. py ", line 137, in calc return eval (expr) File" <string> ", line 1, in <module> ZeroDivisionError: integer division or modulo by zero >>> clc. muffled = True >>> clc. calc ('000000') # blocked Division by zero is illegal
Without parameters after the occurrence T, all exceptions can be captured. You can add an occurrence t statement after the occurrence T, or use tuples in the occurrence t statement to list multiple exception types to capture multiple exceptions, as follows:
Try: x = input (":") y = input (":") print x/yt T (ZeroDivisionError, TypeError), e: print e # The result is as follows >>>: 10: 0 integer division or modulo by zero
You can add an else statement after ty/second t to execute some statements without exception, such
While True: try: x = input (":") y = input (":") print x/y except T Exception, e: print e else: print "Ah ,.... it successed "break # result >>:10: 0 integer division or modulo by zero: 10: 25Ah ,.... it successed
The finally clause-finally clause will certainly be executed. Whether or not exceptions occur in the try clause, it is mainly used to close files or network sockets.