- Make mistakes in your own way
Throws an exception using the Raise statement, which can be used as a raise throw object using a class (which should be a subclass of exception) or an instance parameter. When you use a class, the program automatically creates instances, such as
>>> Raise Exception (' hyperdrive overload ')
Traceback (most recent):
File "<pyshell#8>", line 1, in <module>
Raise Exception (' hyperdrive overload ')
Exception:hyperdrive overload
You can use Try/except to implement catch exceptions, such as
Try: x= Input (":") y= Input (":") Printx/yexceptZerodivisionerror:Print "Hello exception"#结果如下:>>> :10:25>>> :1: 0hello Exception
Throws an exception again, such as
classmuffledcalculator:muffled=FalsedefCalc (self, expr):Try: returneval (expr)exceptZerodivisionerror:ifSelf.muffled:#handle exception if the masking flag is turned on Print "division by zero is illegal" Else:#If the mask flag is not turned on, the exception is thrown again Raise#The results are as follows:>>> CLC =Muffledcalculator ()>>> Clc.calc ('10/2')5>>> Clc.calc ('10/0')#No shieldingTraceback (most recent): File"<pyshell#17>", Line 1,inch<module>Clc.calc ('10/0')#No shieldingFile"E:\work\Code\python\test.py", line 137,inchCalcreturneval (expr) File"<string>", Line 1,inch<module>Zerodivisionerror:integer Divisionormodulo by Zero>>> clc.muffled =True>>> Clc.calc ('10/0')#with shieldingDivision by zero isIllegal
Except can catch all exceptions without parameters, you can catch multiple exceptions by adding a except statement after ty/except or by listing multiple exception types in a except statement as follows:
Try : = Input (":") = input (":") print x/yexcept (Zerodivisionerror, TypeError), E: Print e#结果如下>>> :tenor modulo by zero
Adding an Else statement after Ty/except can execute some statements without throwing an exception, such as
whileTrue:Try: x= Input (":") y= Input (":") Printx/yexceptexception,e:PrinteElse : Print "Ah,.... It successed" Break#Results>>>:10: 0integer Divisionormodulo by zero:10:25Ah,.... It successed
The finally clause-the FINALLY clause is sure to be executed, regardless of whether an exception occurs in a try clause, primarily for closing a file or network socket.
Exceptions to the basic Python tutorial notes